你是如何通过Python(而不是通过Twisted)运行Twisted应用程序的?

Mik*_*cic 19 python sockets networking twisted

我正在通过学​​习Twisted工作,偶然发现了一些我不太确定我非常喜欢的东西 - "Twisted Command Prompt".我正在摆弄我的Windows机器上的Twisted,并尝试运行"聊天"示例:

from twisted.protocols import basic

class MyChat(basic.LineReceiver):
    def connectionMade(self):
        print "Got new client!"
        self.factory.clients.append(self)

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        print "received", repr(line)
        for c in self.factory.clients:
            c.message(line)

    def message(self, message):
        self.transport.write(message + '\n')


from twisted.internet import protocol
from twisted.application import service, internet

factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []

application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
Run Code Online (Sandbox Code Playgroud)

但是,要将此应用程序作为Twisted服务器运行,我必须通过"Twisted命令提示符"运行它,并使用以下命令:

twistd -y chatserver.py
Run Code Online (Sandbox Code Playgroud)

有没有办法更改代码(设置Twisted配置设置等),以便我可以通过以下方式运行它:

python chatserver.py
Run Code Online (Sandbox Code Playgroud)

我用谷歌搜索,但搜索条件似乎太模糊,无法返回任何有意义的回复.

谢谢.

cha*_*.ct 22

我不知道这是否是最好的方法,但我所做的不是:

application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
Run Code Online (Sandbox Code Playgroud)

你可以做:

from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
Run Code Online (Sandbox Code Playgroud)

如果你想要两个选项(twistd和python),那就太过分了:

if __name__ == '__main__':
    from twisted.internet import reactor
    reactor.listenTCP(1025, factory)
    reactor.run()
else:
    application = service.Application("chatserver")
    internet.TCPServer(1025, factory).setServiceParent(application)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Jea*_*one 15

不要混淆"扭曲"与" twistd".当您使用" twistd"时,您正在使用Python运行该程序." twistd"是一个Python程序,除其他外,可以从.tac文件加载应用程序(就像你在这里一样).

"Twisted命令提示符"是Twisted安装程序提供的便利,可以帮助Windows上的人.它所做的只是设置%PATH%包含包含" twistd"程序的目录.如果正确设置%PATH%或使用完整路径调用它,则可以从正常的命令提示符运行twistd.

如果您对此不满意,也许您可​​以扩展您的问题,以包含您在使用" twistd" 时遇到的问题的描述.