Přeskočit na obsah
_CORE
AI & Agentic Systems Core Informační Systémy Cloud & Platform Engineering Data Platforma & Integrace Security & Compliance QA, Testing & Observability IoT, Automatizace & Robotika Mobile & Digital Banky & Finance Pojišťovnictví Veřejná správa Obrana & Bezpečnost Zdravotnictví Energetika & Utility Telco & Média Průmysl & Výroba Logistika & E-commerce Retail & Loyalty
Reference Technologie Blog Knowledge Base O nás Spolupráce Kariéra
Pojďme to probrat

WebSocket Real-time App

01. 01. 2024 1 min čtení intermediate

WebSocket umožňuje obousměrnou real-time komunikaci. Chat, live notifications, collaborative editing.

Server — FastAPI

from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI() connections: list[WebSocket] = [] @app.websocket(“/ws”) async def websocket_endpoint(ws: WebSocket): await ws.accept() connections.append(ws) try: while True: data = await ws.receive_text() for conn in connections: await conn.send_text(f”User: {data}”) except WebSocketDisconnect: connections.remove(ws)

Klient — JavaScript

const ws = new WebSocket(‘ws://localhost:8000/ws’); ws.onopen = () => console.log(‘Connected’); ws.onmessage = (event) => { const msg = event.data; document.getElementById(‘messages’).innerHTML += `

${msg}

`; }; ws.onclose = () => setTimeout(() => location.reload(), 3000); document.getElementById(‘send’).onclick = () => { ws.send(document.getElementById(‘input’).value); };

Klíčový takeaway

WebSocket pro real-time bidirectional komunikaci. Reconnect logic na klientu. Server-Sent Events pro one-way.

websocketreal-timejavascriptpython