gpt4 book ai didi

python - 在单独的线程中运行的高速公路外部的 sendMessage

转载 作者:太空狗 更新时间:2023-10-30 00:10:36 26 4
gpt4 key购买 nike

我想从 MyServerProtocol 类外部调用 sendMessage 方法并向连接的客户端发送消息。我使用 threading 来做到这一点。

当我使用这段代码时:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet import reactor
import threading

class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))

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

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')))

self.sendMessage(payload, isBinary)

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


class Connection(threading.Thread):
def __init__(self):
super(Connection, self).__init__()

def run(self):
self.factory = WebSocketServerFactory("ws://localhost:9000", debug=False)
self.factory.protocol = MyServerProtocol
reactor.listenTCP(9000, self.factory)
reactor.run(installSignalHandlers=0)

def send(self, data):
reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data)

connection = Connection()
connection.daemon = True
connection.start()
connection.send('test')

发生此错误:

connection.send('test')
reactor.callFromThread(self.factory.protocol.sendMessage, self.factory.protocol, data)
AttributeError: 'Connection' object has no attribute 'factory'

如果我尝试注释掉 connection.send('test') 行,则会发生此错误:

TypeError: 'NoneType' object is not iterable

我的代码有什么问题?

我这样做是否正确?或者是否有另一种方法可以从协议(protocol)类外部向客户端发送消息?

谢谢。

最佳答案

is [there] another way to send clients message from outside of server class?

我做这样的事情来发送消息。我使用 twisted 来运行我的网络应用程序。

import json
from autobahn.twisted.websocket import WebSocketServerProtocol
from twisted.internet import reactor

class MyProtocol(WebSocketServerProtocol):
connections = list()

def onConnect(self, request):
self.connections.append(self)

def onClose(self, wasClean, code, reason):
self.connections.remove(self)

@classmethod
def broadcast_message(cls, data):
payload = json.dumps(data, ensure_ascii = False).encode('utf8')
for c in set(cls.connections):
reactor.callFromThread(cls.sendMessage, c, payload)


# Somewhere else
MyProtocol.broadcast_message({'greeting': 'Hello world'})

我不知道它是否是 The Right Way™,但它对我来说效果很好。

关于python - 在单独的线程中运行的高速公路外部的 sendMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799754/

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