# pip install websockets from uvicorn import run from fastapi import FastAPI app = FastAPI(title="websocket") from typing import List from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse html = """ <!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <h1>WebSocket Chat</h1> <h2>Your ID: <span id="ws-id"></span></h2> <form action="" onsubmit="sendMessage(event)"> <input type="text" id="messageText" autocomplete="off"/> <button>Send</button> </form> <ul id='messages'> </ul> <script> var client_id = Date.now() document.querySelector("#ws-id").textContent = client_id; var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`); ws.onmessage = function(event) { var messages = document.getElementById('messages') var message = document.createElement('li') var content = document.createTextNode(event.data) message.appendChild(content) messages.appendChild(message) }; function sendMessage(event) { var input = document.getElementById("messageText") ws.send(input.value) input.value = '' event.preventDefault() } </script> </body> </html> """ 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 get(): return HTMLResponse(html) @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") if __name__ == "__main__": # 启用web服务, reload -> 当改变代码时自动重启 # fastapi_02:app run("__main__:app", reload=True)
标签:__,websocket,fastapi,self,WebSocket,message,id,websockets From: https://www.cnblogs.com/pythonClub/p/17797622.html