运行后 直接输出WebSocket connection is closed.
时间: 2024-03-03 07:50:20 浏览: 165
这可能是由于 WebSocket 连接没有在 `connect` 方法中成功建立造成的。你可以在 `on_error` 方法中添加打印语句,以查看是否有任何错误消息。另外,确保 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!")
```
如果 WebSocket 服务器正在运行,但你仍然无法连接,请检查防火墙设置或代理设置是否阻止了 WebSocket 连接。
阅读全文