通过使用"asyncio"从外部在运行于单独线程中的高速公路中发送sendMessage.

编程入门 行业动态 更新时间:2024-10-23 03:23:39
本文介绍了通过使用"asyncio"从外部在运行于单独线程中的高速公路中发送sendMessage.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想从MyServerProtocol类的外部调用sendMessage方法,并将消息发送到服务器. 该answare 非常与类似 ,但是我需要使用asyncio而不是扭曲的.

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.

推荐答案

call_soon_threadsafe 函数就是为此目的而设计的.

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)

更多推荐

通过使用"asyncio"从外部在运行于单独线程中的高速公路中发送sendMessage.

本文发布于:2023-10-29 08:10:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539173.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   运行于   高速公路   quot   asyncio

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!