最小限の例は、質問をより明確にするのに役立ちます。しかし、長年の 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
呼び出す前に Deferred が失敗するためですreactor.run
。つまり、あなたが実行した時点ですでに失敗しているd.addErrback(listenFailed
ため)、listenFailed
すぐに呼び出されました。
これにはいくつかの解決策があります。1 つは、.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()