代码示例:
import asyncio
import websockets
async def receive_messages():
uri = "ws://localhost:9999/ws"
async with websockets.connect(uri) as websocket:
while True:
# 接收服务端推送的消息
message = await websocket.recv()
print(f"Received: {message}")
# 在这里处理接收到的消息
# ...
# 运行客户端
asyncio.get_event_loop().run_until_complete(receive_messages())