Created
October 20, 2024 19:18
-
-
Save ShilGen/c85e02df24883b45cacd2d06df71f50a to your computer and use it in GitHub Desktop.
Simple FastAPI app with websocket exchange
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 fastapi import FastAPI, WebSocket, WebSocketDisconnect | |
from fastapi.responses import HTMLResponse | |
from typing import List | |
import python_multipart | |
app = FastAPI() | |
# Класс для управления подключениями WebSocket | |
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() | |
# Маршрут для отображения HTML-страницы | |
@app.get("/") | |
async def get(): | |
html_content = """ | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>WebSocket Test</title> | |
</head> | |
<body> | |
<h1>WebSocket с FastAPI</h1> | |
<div id="messages"></div> | |
<input id="messageInput" type="text" autocomplete="off"/> | |
<button onclick="sendMessage()">Отправить</button> | |
<script> | |
const ws = new WebSocket("ws://localhost:8000/ws"); | |
ws.onmessage = function(event) { | |
const messages = document.getElementById('messages'); | |
const message = document.createElement('div'); | |
message.textContent = event.data; | |
messages.appendChild(message); | |
}; | |
function sendMessage() { | |
const input = document.getElementById("messageInput"); | |
ws.send(input.value); | |
input.value = ''; | |
} | |
</script> | |
</body> | |
</html> | |
""" | |
return HTMLResponse(content=html_content) | |
# Эндпоинт WebSocket | |
@app.websocket("/ws") | |
async def websocket_endpoint(websocket: WebSocket): | |
await manager.connect(websocket) | |
try: | |
while True: | |
# Ожидание сообщения от клиента | |
data = await websocket.receive_text() | |
await manager.send_personal_message(f"Вы сказали: {data}", websocket) | |
await manager.broadcast(f"Кто-то сказал: {data}") | |
except WebSocketDisconnect: | |
manager.disconnect(websocket) | |
await manager.broadcast("Клиент отключился") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pip install python-multipart