commit 04735eefa2a20be10a66b9435223e6c7722f870a Author: chimchooree Date: Fri Mar 3 18:03:56 2023 -0600 server sends and receives messages; supports new users joining and chatting diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..14774b4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +websockets diff --git a/server.py b/server.py new file mode 100644 index 0000000..8cef7ee --- /dev/null +++ b/server.py @@ -0,0 +1,28 @@ +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())