Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempt to refactor socket.io server to better integrate with FastAPI server to fix CORS issues #14

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 5 additions & 131 deletions fight_me_backend/main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
#!/usr/bin/env python
import random
import time

import uvicorn
import socketio
import asyncio
import uuid


from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from threading import Thread
from collections import deque
from fastapi_socketio import SocketManager

app = FastAPI()
app.add_middleware(
Expand All @@ -19,131 +16,8 @@
allow_headers=["*"],
)

sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
sio_app = socketio.ASGIApp(sio, other_asgi_app=app)


users = {}
messages = {}
unfilled_rooms = deque()


@app.get("/health")
async def health_check():
return {"status": "ok"}


def broadcast_message():
message = "Hello, clients!"
socketio.emit("broadcast_message", message, broadcast=True)


@sio.on("connect")
def test_connect(sid, data):
print(f"⚡: {sid} user just connected!")
users[sid] = {"room": None}
print(users)


@sio.on("disconnect")
async def test_disconnect(sid):
print(f"🔥: {sid} user disconnected")
sio.leave_room(sid, users[sid]["room"])
users.pop(sid)
await sio.disconnect(sid)
print(users)


@sio.event
async def message(sid, data):
print(f"SID: {sid}")
print(data)

data["timestamp"] = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()))

print(f"Message: {data['text']} from {data['name']} at {data['timestamp']}")

if data.get("room") in messages:
messages[data["room"]].append(data)
else:
messages[data["room"]] = [data]

print(messages)

await sio.emit("messageResponse", data)


@sio.event
async def getMessages(sid, data):
print(f"SID {sid} catching up on messages for room {data['room']}")

print(f"Message history: {messages.get(data['room'])}")
await sio.emit("getMessagesResponse", messages.get(data["room"]))


def getRoomToJoin():
if len(unfilled_rooms):
return unfilled_rooms.popleft()
else:
room = uuid.uuid4().hex
unfilled_rooms.append(room)
return room


@sio.event
async def getRoom(sid):
room = getRoomToJoin()
print(f"Adding SID {sid} to room {room}")
sio.enter_room(sid, room)
users[sid]["room"] = room

topic = "Lorem Ipsum"
side = bool(random.getrandbits(1))

await sio.emit("getRoomResponse", {"room": room, "topic": topic, "side": side})


@sio.event
async def leaveRoom(sid, data):
print(f"Removing SID {sid} from room {data['room']}")
sio.leave_room(sid, data["room"])

num_in_room = sum(1 for _, user_data in users.items() if user_data.get("room") is data["room"])
print(f"Num left in room: {num_in_room}")
if num_in_room > 0:
unfilled_rooms.append(data["room"])

users[sid]["room"] = None
await sio.emit("leaveRoomResponse", {"room": data["room"]}, to=sid)


async def connected_users():
users_in_rooms = sum(1 for _, user_data in users.items() if user_data.get("room") is not None)
await sio.emit("connectedUsers", {"users": len(users), "usersInRooms": users_in_rooms})


async def connected_users_timer(interval_seconds):
while True:
await connected_users()
await asyncio.sleep(interval_seconds)


def start_connected_users_timer():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

try:
loop.create_task(connected_users_timer(2))
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
finally:
loop.close()


thread = Thread(target=start_connected_users_timer, daemon=True)
thread.start()
socket_manager = SocketManager(app=app)


if __name__ == "__main__":
uvicorn.run(sio_app, host="0.0.0.0", port=5000)
uvicorn.run(app, host="0.0.0.0", port=5000)
129 changes: 129 additions & 0 deletions fight_me_backend/socket_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import random
import time
import asyncio
import uuid
from threading import Thread
from collections import deque

from .main import app, socket_manager as sm

users = {}
messages = {}
unfilled_rooms = deque()


@app.get("/health")
async def health_check():
return {"status": "ok"}


def broadcast_message():
message = "Hello, clients!"
sm.emit("broadcast_message", message, broadcast=True)


@app.sio.on("connect")
def test_connect(sid, data):
print(f"⚡: {sid} user just connected!")
users[sid] = {"room": None}
print(users)


@app.sio.on("disconnect")
async def test_disconnect(sid):
print(f"🔥: {sid} user disconnected")
app.sio.leave_room(sid, users[sid]["room"])
users.pop(sid)
await app.sio.disconnect(sid)
print(users)


@app.sio.event
async def message(sid, data):
print(f"SID: {sid}")
print(data)

data["timestamp"] = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()))

print(f"Message: {data['text']} from {data['name']} at {data['timestamp']}")

if data.get("room") in messages:
messages[data["room"]].append(data)
else:
messages[data["room"]] = [data]

print(messages)

await app.sio.emit("messageResponse", data)


@app.sio.event
async def getMessages(sid, data):
print(f"SID {sid} catching up on messages for room {data['room']}")

print(f"Message history: {messages.get(data['room'])}")
await app.sio.emit("getMessagesResponse", messages.get(data["room"]))


def getRoomToJoin():
if len(unfilled_rooms):
return unfilled_rooms.popleft()
else:
room = uuid.uuid4().hex
unfilled_rooms.append(room)
return room


@app.sio.event
async def getRoom(sid):
room = getRoomToJoin()
print(f"Adding SID {sid} to room {room}")
app.sio.enter_room(sid, room)
users[sid]["room"] = room

topic = "Lorem Ipsum"
side = bool(random.getrandbits(1))

await app.sio.emit("getRoomResponse", {"room": room, "topic": topic, "side": side})


@app.sio.event
async def leaveRoom(sid, data):
print(f"Removing SID {sid} from room {data['room']}")
app.sio.leave_room(sid, data["room"])

num_in_room = sum(1 for _, user_data in users.items() if user_data.get("room") is data["room"])
print(f"Num left in room: {num_in_room}")
if num_in_room > 0:
unfilled_rooms.append(data["room"])

users[sid]["room"] = None
await app.sio.emit("leaveRoomResponse", {"room": data["room"]}, to=sid)


async def connected_users():
users_in_rooms = sum(1 for _, user_data in users.items() if user_data.get("room") is not None)
await app.sio.emit("connectedUsers", {"users": len(users), "usersInRooms": users_in_rooms})


async def connected_users_timer(interval_seconds):
while True:
await connected_users()
await asyncio.sleep(interval_seconds)


def start_connected_users_timer():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

try:
loop.create_task(connected_users_timer(2))
loop.run_forever()
except KeyboardInterrupt:
loop.stop()
finally:
loop.close()


thread = Thread(target=start_connected_users_timer, daemon=True)
thread.start()
21 changes: 20 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ python = "^3.11"
python-socketio = "^5.8.0"
uvicorn = {extras = ["standard"], version = "^0.22.0"}
fastapi = "^0.95.2"
fastapi-socketio = "^0.0.10"


[tool.poetry.group.dev.dependencies]
Expand Down