1. 服务端
import asyncio
import websockets
async def echo(ws):
async for message in ws:
print(f"Received message: {message}")
await ws.send(f"你好,收到你的消息: {message}")
async def main():
print("WebSocket服务器启动,等待客户端连接...")
async with websockets.serve(echo, "localhost", 12345):
await asyncio.Future()
asyncio.run(main())
2. 客户端
import asyncio
import websockets
async def hello():
uri = "ws://localhost:12345"
async with websockets.connect(uri) as ws:
name = "你好!"
await ws.send(name)
print(f"发送成功: {name}")
greeting = await ws.recv()
print(f"收到响应: {greeting}")
asyncio.run(hello())
3. 使用效果
3.1 环境准备
pip install websockets

3.2 启动服务器
python server.py

3.3 启动客户端
python client.py
