我想从MyServerProtocol类外部调用sendMessage方法,并向服务器发送消息。 answare 非常类似于this ,但我需要使用asyncio而不是扭曲。
Cane有人建议我解决方案吗?从this派生的示例也将受到赞赏 感谢。
答案 0 :(得分:0)
事件循环的call_soon_threadsafe
函数就是为此而设的。
from autobahn.asyncio.websocket import WebSocketServerProtocol, \
WebSocketServerFactory
class MyServerProtocol(WebSocketServerProtocol):
loop = None
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')))
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
@classmethod
def broadcast_message(cls, data):
payload = json.dumps(data, ensure_ascii = False).encode('utf8')
for c in set(cls.connections):
self.loop.call_soon_threadsafe(cls.sendMessage, c, payload)
factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
factory.protocol = MyServerProtocol
loop = asyncio.get_event_loop()
MyServerProtocol.loop = loop
coro = loop.create_server(factory, '0.0.0.0', 9000)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
server.close()
loop.close()
然后从另一个线程中调用
MyServerProtocol.broadcast_message(payload)