feat(server): MVP socketio integration

parent fbedea4c
from fastapi import FastAPI, APIRouter from http.client import HTTPException
import socketio
from fastapi import FastAPI, APIRouter, HTTPException
from starlette.websockets import WebSocket 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() 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("/") @router.get("/")
...@@ -16,7 +31,11 @@ async def hello_world(): ...@@ -16,7 +31,11 @@ async def hello_world():
@router.post("/join") @router.post("/join")
async def join(player_name: str): 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") @router.post("/ready")
......
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)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment