You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
921 B
Python

import asyncio
import json
import websockets
connected = []
IDs = {}
async def handler(websocket):
await websocket.send(json.dumps({"type": "test", "message": "test packet from server"}))
async for original in websocket:
packet = json.loads(original)
print(packet)
if packet["type"] == "user_joined":
IDs[websocket] = packet["name"]
connected.append(websocket)
websockets.broadcast(connected, json.dumps({"type": "server_message", "message": IDs[websocket] + " joined"}))
elif packet["type"] == "shout" or packet['type'] == "server_message":
websockets.broadcast(connected, json.dumps({"type": "shout", "name": IDs[websocket], "message": packet["message"]}))
async def main():
async with websockets.serve(handler, "", 8080):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())