(20200423已解决)Sanic.websocket出现RuntimeError: this event loop is already running.

  • 问题描述

    运行Sanic WebSocket服务器,出现如题错误。

  • 解决方案

    原因是在app.websockt('/')下的async def内又一次调用了loop=asyncio.get_event_loop().

    Sanicapp.run()其实内部已经起了一个event_loop.

    async def内的loop=asyncio.get_event_loop()取消,改用await关键字将所需要执行的coroutine calls添加到已启动的event loop中就可以了。

这个错误通常是由于在 WebSocket 连接已关闭的情况下,尝试发送或接收消息。为了防止这个错误,你可以在发送消息之前检查 WebSocket 连接的状态,如果连接已关闭,则不发送消息。下面是一个修改后的示例: ```python import websocket import threading class WebSocketClient: def __init__(self, url): self.url = url self.ws = None self.connect() def connect(self): self.ws = websocket.WebSocketApp(self.url, on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close) self.wst = threading.Thread(target=self.ws.run_forever) self.wst.daemon = True self.wst.start() def on_open(self, ws): print("WebSocket connection established") def on_message(self, ws, message): print("Received message:", message) def on_error(self, ws, error): print("WebSocket error:", error) def on_close(self, ws): print("WebSocket connection closed") def send(self, message): if self.ws and self.ws.sock and self.ws.sock.connected: self.ws.send(message) else: print("WebSocket connection is closed.") def close(self): self.ws.close() if __name__ == "__main__": ws = WebSocketClient("ws://localhost:8080") ws.send("Hello, WebSocket Server!") ``` 在 `send` 方法中,我们添加了一些代码来检查 WebSocket 连接的状态。如果连接已关闭,则不发送消息,并打印一条错误信息。这样,在尝试发送消息之前,我们始终会检查 WebSocket 连接的状态,从而避免出现 `WebSocketConnectionClosedException` 异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值