我正在努力学习 Twisted,并且偶然发现了一些我不确定自己是否非常喜欢的东西 - “Twisted 命令提示符”。我在我的 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)
但是,要将这个应用程序作为 Twisted 服务器运行,我必须通过“Twisted 命令提示符”运行它,命令如下:
twistd -y chatserver.py
有什么方法可以更改代码(设置 Twisted 配置设置等),以便我可以简单地通过以下方式运行它:
python chatserver.py
我用 Google 搜索过,但搜索词似乎太模糊,无法返回任何有意义的响应。
谢谢。
最佳答案
我不知道这是否是最好的方法,但我所做的是:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
你可以这样做:
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
总结一下,如果你想要两个选项(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)
希望对你有帮助!
关于python - 您如何通过 Python(而不是通过 Twisted)运行 Twisted 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1897939/