diff --git a/server/app.py b/server/app.py index 9ffd6e7..d78f0d4 100644 --- a/server/app.py +++ b/server/app.py @@ -1,12 +1,27 @@ -from fastapi import FastAPI, APIRouter +from http.client import HTTPException + +import socketio +from fastapi import FastAPI, APIRouter, HTTPException from starlette.websockets import WebSocket -from server.model.data import Game, Player +from server.model.data import Game +# Game state +from server.model.players import RandomPlayer +from server.ws import sio -app = FastAPI() +game = Game() +# Server +app = FastAPI() router = APIRouter() -game = Game() + +# Create and mount SocketIO app +sio_asgi_app = socketio.ASGIApp( + socketio_server=sio, + other_asgi_app=app +) +app.add_route("/socket.io/", route=sio_asgi_app, methods=['GET', 'POST']) +app.add_websocket_route("/socket.io/", sio_asgi_app) @router.get("/") @@ -16,7 +31,11 @@ async def hello_world(): @router.post("/join") async def join(player_name: str): - game.players.append(Player(player_name)) + if game.add_player(RandomPlayer(player_name) # TODO: Let user play + ): + return "Welcome %s, %i players currently waiting!" % (player_name, len(game.players)) + else: + raise HTTPException(status_code=403, detail=f"{player_name} already connected, choose another name.") @router.post("/ready") diff --git a/server/ws.py b/server/ws.py new file mode 100644 index 0000000..bf728d5 --- /dev/null +++ b/server/ws.py @@ -0,0 +1,19 @@ +import socketio + +sio = socketio.AsyncServer( + async_mode='asgi', + # cors_allowed_origins=','.join(config.ALLOW_ORIGIN) +) + +@sio.event +def connect(sid, environ): + print("connect ", sid, environ) + +@sio.event +async def chat_message(sid, data): + print("message ", data) + await sio.emit('reply', room=sid) + +@sio.event +def disconnect(sid): + print('disconnect ', sid)