gpt4 book ai didi

python-2.7 - 在 Twisted 中关闭连接后退出 Python 程序

转载 作者:行者123 更新时间:2023-12-01 04:34:23 24 4
gpt4 key购买 nike

所以我有这个小项目,它使用 python 中的 websockets 来自 autobahn twisted。客户端和服务器之间的连接以及数据传输工作正常,但在 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

最佳答案

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

reactor.run()
reactor.stop()

意思是:

Run forever. After "forever" is done, stop running.

在您提出问题的方式中有一个线索:您说您想“在 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 来停止整个 react 堆。

那看起来更像这样: 导入系统 从某处.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:])

希望这对您有所帮助!

关于python-2.7 - 在 Twisted 中关闭连接后退出 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31078728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com