一個簡單的例子可以幫助你更清楚地問你的問題。然而,根據多年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