报错了 websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.
时间: 2024-03-03 09:50:18 浏览: 335
这个错误通常是由于在 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` 异常。
阅读全文