[英]Exiting Twisted-application after listenFailure
我剛開始學習twisted並使用Tcp4endpoint類編寫了一個小的tcp服務器/客戶端。 除了一件事,一切都很好。
為了檢測將不可用端口作為監聽端口提供給服務器的事件,我向端點 - 仲裁器添加了一個錯誤。 這個errback被觸發,但是,我無法從errback退出應用程序。 Reactor.stop導致另一個失敗,說反應堆沒有運行,而例如sys.exit觸發另一個錯誤。 只有當我按ctrl + c和gc命中時才會看到后者的輸出。
我的問題是,有沒有辦法讓listenFailure發生后應用程序退出(干凈利落)?
一個最小的例子將有助於使您的問題更加清晰。 然而,基於扭曲多年的經驗,我有一個有根據的猜測。 我想你寫的程序是這樣的:
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
調用了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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.