Skip to content

Commit

Permalink
added more livelit demos
Browse files Browse the repository at this point in the history
  • Loading branch information
gcrois committed Nov 8, 2024
1 parent 6aca330 commit 1a75592
Show file tree
Hide file tree
Showing 5 changed files with 567 additions and 18 deletions.
42 changes: 42 additions & 0 deletions browsertest/src/game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import asyncio
import websockets
import json

PORT = 8765

connected_clients = set()
game_state = {
"players": {}
}

async def handler(websocket, path):
connected_clients.add(websocket)
player_id = None
try:
async for message in websocket:
data = json.loads(message)
if data['type'] == 'join':
player_id = data['player']['id']
game_state['players'][player_id] = data['player']
await broadcast_game_state()
elif data['type'] == 'move' and player_id is not None:
game_state['players'][player_id] = data['player']
await broadcast_game_state()
except websockets.exceptions.ConnectionClosed:
pass
finally:
if player_id is not None and player_id in game_state['players']:
del game_state['players'][player_id]
await broadcast_game_state()
connected_clients.remove(websocket)

async def broadcast_game_state():
if connected_clients:
message = json.dumps({"type": "state", "state": game_state})
# Create tasks explicitly for each send operation
await asyncio.gather(*(asyncio.create_task(client.send(message)) for client in connected_clients))

start_server = websockets.serve(handler, "localhost", PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
37 changes: 37 additions & 0 deletions browsertest/src/websocket.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import asyncio
import websockets
from websockets.server import WebSocketServerProtocol
from typing import Set

connected_clients: Set[WebSocketServerProtocol] = set()

async def echo(websocket: WebSocketServerProtocol, path: str) -> None:
print("Client connected")
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message from client: {message}")
if connected_clients:
await asyncio.gather(*(client.send(f"{message}") for client in connected_clients if client != websocket))
else:
print("No clients connected")
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)

async def console_input() -> None:
while True:
message = await asyncio.get_event_loop().run_in_executor(None, input, "Enter message to broadcast: ")
if connected_clients:
await asyncio.gather(*(client.send(f"{message}") for client in connected_clients))
else:
print("No clients connected")

async def main() -> None:
async with websockets.serve(echo, "localhost", 8765):
print("WebSocket server running on ws://localhost:8765")
await asyncio.gather(console_input(), asyncio.Future()) # Run console input and server forever

if __name__ == "__main__":
asyncio.run(main())
Loading

0 comments on commit 1a75592

Please sign in to comment.