【发布时间】:2023-03-28 13:05:01
【问题描述】:
我打算写一个类WebsocketHandler来包装包websockets
这是代码:
import asyncio
import websockets
class WebsocketHandler:
__connection = None
def __init__(self):
asyncio.run(self.__setConnection())
async def __setConnection(self):
async with websockets.connect("ws://localhost/your/path") as websocket:
self.__connection = websocket
print("Connected")
def send(self, msg):
self.__connection.send(msg)
print("message Send")
ws = WebsocketHandler()
ws.send("message")
对于服务器部分,我有另一个完成的脚本,它可以在我有新连接、收到消息以及客户端断开连接时向我发送消息(与其他语言的其他脚本一起测试)。
当我尝试它时,脚本成功连接到我的 websocket 服务器(脚本打印 Connected 并且在服务器端我得到了一个新连接)。
然后我在脚本中收到警告
RuntimeWarning: coroutine 'WebSocketCommonProtocol.send' was never awaited
self.__connection.send(msg)
然后我的脚本打印 Message send 并停止。
问题是在服务器端我没有收到消息的事实,而只有一个告诉我客户端已断开连接的消息。基本上脚本不会发送消息,也不会产生错误。
有人知道问题出在哪里吗?
【问题讨论】:
标签: python asynchronous websocket