参考
其他
- keepalive 超时退出的问题,同时修改服务端和客户端的超时逻辑,比如 ping_timeout=1200, ping_interval=None;参考 https://websockets.readthedocs.io/en/stable/topics/timeouts.html
- API 接口设置 服务端和客户端的接口定义;https://websockets.readthedocs.io/en/stable/reference/server.html
demo
import asyncio
import websockets
CONNECTIONS = set()
async def serverRun(websocket, path):
CONNECTIONS.add(websocket)
print(path)
if path == "/broadcast":
await websocket.send("hi")
async for message in websocket:
print("broadcast: ", message, 'received from client')
websockets.broadcast(CONNECTIONS, message)
else:
await websocket.send("hi")
async for message in websocket:
print(message, 'received from client')
greeting = f"Hello {message}!"
await websocket.send(greeting)
print(f"> {greeting}")
IP_PORT = 8764
IP_ADDR = "127.0.0.1"
server = websockets.serve(serverRun, IP_ADDR, IP_PORT)
asyncio.get_event_loop().run_until_complete(server)
asyncio.get_event_loop().run_forever()