5.1 KiB
5.1 KiB
In [ ]:
import websocket
import json
def on_open(ws):
print("WebSocket 连接已建立")
# 发送文本消息
ws.send("Hello, WebSocket Server!")
# 发送 JSON 消息
data = {"type": "message", "content": "这是JSON数据"}
ws.send(json.dumps(data))
def on_message(ws, message):
print(f"收到服务器消息: {message}")
def on_close(ws, close_status_code, close_msg):
print("连接已关闭")
if __name__ == "__main__":
# WebSocket 服务器地址
ws_url = "ws://192.168.0.125:58080/webSocket" # 测试用公共服务器
# 创建 WebSocket 连接
ws = websocket.WebSocketApp(
ws_url,
on_open=on_open,
on_message=on_message,
on_close=on_close
)
# 启动连接(阻塞模式)
ws.run_forever()[1;31m---------------------------------------------------------------------------[0m [1;31mRuntimeError[0m Traceback (most recent call last) Cell [1;32mIn[1], line 22[0m [0;32m 17[0m [38;5;66;03m# # 接收服务器响应[39;00m [0;32m 18[0m [38;5;66;03m# response = await ws.recv()[39;00m [0;32m 19[0m [38;5;66;03m# print(f"收到服务器消息: {response}")[39;00m [0;32m 21[0m [38;5;28;01mif[39;00m [38;5;18m__name__[39m [38;5;241m==[39m [38;5;124m"[39m[38;5;124m__main__[39m[38;5;124m"[39m: [1;32m---> 22[0m asyncio[38;5;241m.[39mget_event_loop()[38;5;241m.[39mrun_until_complete(send_message()) File [1;32md:\Anaconda3\Lib\asyncio\base_events.py:663[0m, in [0;36mBaseEventLoop.run_until_complete[1;34m(self, future)[0m [0;32m 652[0m [38;5;250m[39m[38;5;124;03m"""Run until the Future is done.[39;00m [0;32m 653[0m [0;32m 654[0m [38;5;124;03mIf the argument is a coroutine, it is wrapped in a Task.[39;00m [1;32m (...)[0m [0;32m 660[0m [38;5;124;03mReturn the Future's result, or raise its exception.[39;00m [0;32m 661[0m [38;5;124;03m"""[39;00m [0;32m 662[0m [38;5;28mself[39m[38;5;241m.[39m_check_closed() [1;32m--> 663[0m [38;5;28mself[39m[38;5;241m.[39m_check_running() [0;32m 665[0m new_task [38;5;241m=[39m [38;5;129;01mnot[39;00m futures[38;5;241m.[39misfuture(future) [0;32m 666[0m future [38;5;241m=[39m tasks[38;5;241m.[39mensure_future(future, loop[38;5;241m=[39m[38;5;28mself[39m) File [1;32md:\Anaconda3\Lib\asyncio\base_events.py:622[0m, in [0;36mBaseEventLoop._check_running[1;34m(self)[0m [0;32m 620[0m [38;5;28;01mdef[39;00m [38;5;21m_check_running[39m([38;5;28mself[39m): [0;32m 621[0m [38;5;28;01mif[39;00m [38;5;28mself[39m[38;5;241m.[39mis_running(): [1;32m--> 622[0m [38;5;28;01mraise[39;00m [38;5;167;01mRuntimeError[39;00m([38;5;124m'[39m[38;5;124mThis event loop is already running[39m[38;5;124m'[39m) [0;32m 623[0m [38;5;28;01mif[39;00m events[38;5;241m.[39m_get_running_loop() [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m: [0;32m 624[0m [38;5;28;01mraise[39;00m [38;5;167;01mRuntimeError[39;00m( [0;32m 625[0m [38;5;124m'[39m[38;5;124mCannot run the event loop while another loop is running[39m[38;5;124m'[39m) [1;31mRuntimeError[0m: This event loop is already running