sendMessage from outside in autobahn running in separate thread by using “asyncio”

泪湿孤枕 提交于 2020-01-24 20:00:11

问题


I want to call sendMessage method from outside of MyServerProtocol class and send a message to the server. The answare is very similar to this but i need to use asyncio instead of twisted.

Cane someone suggest me a solution? An example derived from this would also be appreciated Thanks.


回答1:


The call_soon_threadsafe function of event loop is meant for this.

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)


来源:https://stackoverflow.com/questions/44953509/sendmessage-from-outside-in-autobahn-running-in-separate-thread-by-using-asynci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!