WebSocket 服务
使用Python FastAPI框架官网demo,官网地址:https://fastapi.tiangolo.com/zh/advanced/websockets/
#!/usr/bin/env python # -*- coding: utf-8 -*- # @time: 2021/12/9 6:30 下午 import uvicorn from typing import List from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse app = FastAPI() 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:8010/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) @classmethod async def send_personal_message(cls, message: str, websocket: WebSocket): await websocket.send_text(message) async def broadcast(self, message: str, websocket: WebSocket = None): for connection in self.active_connections: if connection != websocket: 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"你说了: {data}", websocket) await manager.broadcast(f"用户:{client_id} 说: {data}", websocket) except WebSocketDisconnect: manager.disconnect(websocket) await manager.broadcast(f"用户-{client_id}-离开") if __name__ == '__main__': uvicorn.run('main:app', debug=True, host='0.0.0.0', port=8010)