Created
October 22, 2022 02:32
-
-
Save vndee/c59511f24196a79701d8ce537b302fbb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List | |
from fastapi import FastAPI | |
from fastapi import WebSocket, Request, WebSocketDisconnect | |
from fastapi.templating import Jinja2Templates | |
templates = Jinja2Templates("template") | |
app = FastAPI(title="Demo WebSocket Chatroom") | |
class ConnectionManager: | |
def __init__(self): | |
self.active_connections: List[WebSocket] = [] | |
async def connect(self, websocket: WebSocket): | |
await websocket.accept() | |
self.active_connections.append(websocket) | |
def disconnect(self, websocket: WebSocket): | |
self.active_connections.remove(websocket) | |
async def send_personal_message(self, message: str, websocket: WebSocket): | |
await websocket.send_text(message) | |
async def broadcast(self, message: str): | |
for connection in self.active_connections: | |
await connection.send_text(message) | |
manager = ConnectionManager() | |
@app.get("/") | |
async def home(request: Request): | |
template = "index.html" | |
context = {"request": request} | |
return templates.TemplateResponse(template, context) | |
@app.websocket("/ws/{client_id}") | |
async def websocket_endpoint(websocket: WebSocket, client_id: int): | |
await manager.connect(websocket) | |
try: | |
while True: | |
data = await websocket.receive_text() | |
await manager.send_personal_message(f"You wrote: {data}", websocket) | |
await manager.broadcast(f"Client #{client_id} says: {data}") | |
except WebSocketDisconnect: | |
manager.disconnect(websocket) | |
await manager.broadcast(f"Client #{client_id} left the chat") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment