brodcast added
This commit is contained in:
@@ -1,21 +1,34 @@
|
|||||||
import websockets;
|
import websockets
|
||||||
import asyncio;
|
import asyncio
|
||||||
|
|
||||||
|
connected = set()
|
||||||
|
|
||||||
async def handler(websocket):
|
async def handler(websocket):
|
||||||
while True:
|
# Register.
|
||||||
#Save the incoming message in variable message.
|
connected.add(websocket)
|
||||||
message = await websocket.recv()
|
try:
|
||||||
print(message)
|
while True:
|
||||||
|
message = await websocket.recv()
|
||||||
|
print(message)
|
||||||
|
await broadcast(message)
|
||||||
|
except websockets.ConnectionClosedOK:
|
||||||
|
print("Client disconnected")
|
||||||
|
finally:
|
||||||
|
connected.remove(websocket)
|
||||||
|
|
||||||
|
async def broadcast(message):
|
||||||
|
if connected: # asyncio.wait doesn't accept an empty list
|
||||||
|
await asyncio.wait([ws.send(message) for ws in connected])
|
||||||
|
|
||||||
|
async def sendClientId():
|
||||||
|
if connected: # asyncio.wait doesn't accept an empty list
|
||||||
|
await asyncio.wait([ws.send(message) for ws in connected])
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
async with websockets.serve(handler, "145.92.8.114" , 8001):
|
async with websockets.serve(handler, "0.0.0.0", 8001):
|
||||||
await asyncio.Future() # run forever
|
await asyncio.Future() # run forever
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
#https://websockets.readthedocs.io/en/stable/reference/sync/server.html#websockets.sync.server.serve
|
#https://websockets.readthedocs.io/en/stable/reference/sync/server.html#websockets.sync.server.serve
|
Reference in New Issue
Block a user