【问题标题】:Exiting Python Program after closing connection in Twisted在 Twisted 中关闭连接后退出 Python 程序
【发布时间】:2015-06-26 17:17:59
【问题描述】:

所以我有一个小项目,它使用来自 autobahn twisted 的 python 中的 websockets。客户端和服务器之间的连接以及数据传输工作完美,但在 TCP 连接关闭后我无法正常退出程序。她的就是代码:

class MyClientProtocol(WebSocketClientProtocol):

    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))

    def onOpen(self):
        print("WebSocket connection open.")

        def hello():
            from twisted.internet import reactor
            self.sendMessage(u"Hello, world!".encode('utf8'))
            self.sendMessage(b"\x00\x01\x03\x04", isBinary=True)

            #self.factory.reactor.callLater(1, hello)
            #self.reactor.callFromThread(reactor.stop)
            #reactor.callFromThread(reactor.stop)
            #self.factory.reactor.callFromThread(reactor.stop)
        # start sending messages every second ..
        hello()
        return

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


def WebCon():
    import sys

    from twisted.python import log
    from twisted.internet import reactor

    log.startLogging(sys.stdout)

    factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
    factory.protocol = MyClientProtocol

    reactor.connectTCP("127.0.0.1", 8080, factory)

    reactor.run()
    reactor.stop()
    print("Should exit")
    return

【问题讨论】:

  • 也许使用quit() 方法是可行的方法?
  • 试过 sys,exit 和 quit ,它们都不起作用。

标签: python-2.7 websocket twisted autobahn


【解决方案1】:

reactor.run() 永远运行。所以这两行

reactor.run()
reactor.stop()

意思是:

永远奔跑。 “永远”完成后,停止运行。

你问问题的方式有一个线索:你说你想“在 TCP 连接关闭后优雅地[退出]程序”。由于您的程序是现在编写的,因此您可以在程序准备好退出后优雅地退出程序。

连接关闭是一个事件。在 Twisted 中,您会通过在对象上调用的方法收到事件通知。幸运的是,您已经获得了对象,并且您甚至已经实现了适当的方法!你只需要改变

def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))

def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))
    reactor.stop()

对于更惯用的解决方案,您应该使用endpoints,而不是connectTCP,来建立您的传出连接,并使用react,而不是reactor.run(),来运行您的主循环。看起来您想编写一个更像“连接,然后在我的连接上执行操作,然后等待连接关闭,然后退出”的函数,而不是硬编码 onClose 以停止整个反应器。

看起来更像这样: 导入系统 从某处.i.dont.know 导入(WebSocketClientProtocol, WebSocketClientFactory)

from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.task import react
from twisted.internet.endpoints import clientFromString

from twisted.logger import globalLogBeginner, textFileLogObserver

class MyClientProtocol(WebSocketClientProtocol):

    def __init__(self):
        self.finished = Deferred()

    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))

    def onOpen(self):
        print("WebSocket connection open.")
        self.sendMessage(u"Hello, world!".encode('utf8'))
        self.sendMessage(b"\x00\x01\x03\x04", isBinary=True)

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))
        self.finished.callback(None)


@inlineCallbacks
def WebCon(reactor, endpoint="tcp:127.0.0.1:80"):
    globalLogBeginner.beginLoggingTo(textFileLogObserver(sys.stdout))

    factory = WebSocketClientFactory("ws://localhost:8080", debug=False)
    factory.protocol = MyClientProtocol

    endpoint = clientFromString(reactor, endpoint)
    protocol = yield endpoint.connect(factory)
    yield protocol.finished

react(WebCon, sys.argv[1:])

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2020-01-08
    相关资源
    最近更新 更多