-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
50 lines (40 loc) · 1.62 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from fastapi import FastAPI, WebSocket, Request
from fastapi.templating import Jinja2Templates
from typing import Dict, Set
from fastapi.websockets import WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
import json
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
# 部屋ごとのWebSocket接続を管理
room_websockets: Dict[str, Set[WebSocket]] = {}
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.websocket("/ws/{room_name}")
async def websocket_endpoint(websocket: WebSocket, room_name: str):
await websocket.accept()
if room_name not in room_websockets:
room_websockets[room_name] = set()
room_websockets[room_name].add(websocket)
print(room_websockets)
#メッセージのやり取り、退出判定
try:
while True:
data = await websocket.receive_text()
data = json.loads(data)
print(data)
userName = data.get("userName", "Unknown User")
message = data.get("message", "")
response_data = {
"userName": userName,
"message": message
}
for ws in room_websockets.get(room_name, []):
await ws.send_text(json.dumps(response_data))
except WebSocketDisconnect:
room_websockets[room_name].remove(websocket)
if not room_websockets[room_name]:
del room_websockets[room_name]
print(room_websockets)