一个简单的例子可以帮助你更清楚地问你的问题。然而,根据多年Twisted的经验,我有一个有教养的猜测。我觉得你写了一个程序是这样的:
from twisted.internet import endpoints, reactor, protocol
factory = protocol.Factory()
factory.protocol = protocol.Protocol
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8000)
d = endpoint.listen(factory)
def listenFailed(reason):
reactor.stop()
d.addErrback(listenFailed)
reactor.run()
你是在正确的轨道上。不幸的是,你有一个订购问题。 reactor.stop
因ReactorNotRunning
而失败的原因在于listen
延迟失败,因此请拨打reactor.run
。也就是说,在你做d.addErrback(listenFailed
时它已经失败了,所以listenFailed
立即被调用。
有很多解决方案。一个是写一个.tac文件和使用服务:
from twisted.internet import endpoints, reactor, protocol
from twisted.application.internet import StreamServerEndpointService
from twisted.application.service import Application
application = Application("Some Kind Of Server")
factory = protocol.Factory()
factory.protocol = protocol.Protocol
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8000)
service = StreamServerEndpointService(endpoint, factory)
service.setServiceParent(application)
这是使用twistd
运行,像twistd -y thisfile.tac
另一种选择是使用的服务是基于低层特征,reactor.callWhenRunning
:
from twisted.internet import endpoints, reactor, protocol
factory = protocol.Factory()
factory.protocol = protocol.Protocol
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8000)
def listen():
d = endpoint.listen(factory)
def listenFailed(reason):
reactor.stop()
d.addErrback(listenFailed)
reactor.callWhenRunning(listen)
reactor.run()
谢谢你的答案! – 2012-08-18 07:16:27