Как использовать автобан sendmessage() из отдельного потока (asyncio)?

Я хочу использовать sendMessage() снаружи MyServerProtocol из отдельного потока для отправки сообщения клиенту.

Я пытаюсь сделать что-то очень похожее на this и < href="https://stackoverflow.com/questions/44953509/sendmessage-from-outside-in-autobahn-running-in-separate-thread-by-using-asynci">это, которое не Работа.

Первое решение использует Twisted, а второе использует `broadcast_message()', что выдает следующую ошибку

for c in set(cls.connections):
AttributeError: type object 'MyServerProtocol' has no attribute 'connections'

Мой код:

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 = bytes(data, encoding='utf8')
        for c in set(cls.connections):
            self.loop.call_soon_threadsafe(cls.sendMessage, c, payload)
if __name__ == '__main__':
    import asyncio
    factory = WebSocketServerFactory(u"ws://127.0.0.1:9080")
    factory.protocol = MyServerProtocol
    loop = asyncio.get_event_loop()
    MyServerProtocol.loop = loop
    coro = loop.create_server(factory, '0.0.0.0', 9080)
    server = loop.run_until_complete(coro)
    vad_thread = threading.Thread(target=main, args=(ARGS,))
    vad_thread.start()

    try:
        loop.run_forever()
        print("this will not print")
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()

Из vad_thread я позвонил:

MyServerProtocol.broadcast_message(payload)

который выдает вышеупомянутую ошибку.

Мне нужна функция, скажем, send_message(payload), которая отправляет полезную нагрузку клиенту.


person cpfour    schedule 21.04.2019    source источник