[英]sendMessage from outside in autobahn running in separate thread by using “asyncio”
I want to call sendMessage method from outside of MyServerProtocol class and send a message to the server. 我想从MyServerProtocol类之外调用sendMessage方法,并将消息发送到服务器。 The answare is very similar to this but i need to use asyncio instead of twisted .
answare与此 非常相似, 但是我需要使用asyncio而不是twisted 。
Cane someone suggest me a solution? 有人可以给我建议解决方案吗? An example derived from this would also be appreciated Thanks.
衍生自一个例子这也将被理解的感谢。
The call_soon_threadsafe
function of event loop is meant for this. 事件循环的
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()
And then from the other thread simply invoke 然后从另一个线程简单地调用
MyServerProtocol.broadcast_message(payload)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.