Reference resources
- html demo https://www.runoob.com/html/html5-websocket.html
- python websockets Use , Realization server and client Communication for https://blog.csdn.net/liranke/article/details/120533682
- Official documents https://websockets.readthedocs.io/en/stable/intro/index.html
demo
import asyncio
import websockets
CONNECTIONS = set()
# https://websockets.readthedocs.io/en/stable/intro/index.html
# https://www.runoob.com/html/html5-websocket.html
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()