WebSockets para comunicación en tiempo real
Cree funcionalidades en tiempo real en FastAPI con WebSockets: acepte conexiones, intercambie mensajes, difúndalos a varios clientes y gestione las desconexiones correctamente mediante patrones asíncronos.
WebSockets para comunicación en tiempo real es una lección gratuita de FastAPI Backend Development Bootcamp en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de FastAPI Backend Development Bootcamp, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de FastAPI Backend Development Bootcamp incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
From Request/Response to Real-Time
Regular HTTP is request/response: the client asks, the server answers, the connection closes. WebSockets keep a single connection open for full-duplex, real-time messaging. Perfect for chat, live dashboards, and notifications.
Why Async Fits WebSockets
A WebSocket connection lives a long time and is mostly idle waiting for messages. FastAPI's async model lets one worker handle thousands of concurrent connections without blocking.
A Minimal WebSocket Endpoint
Declare a @app.websocket route. Accept the connection, then loop receiving and sending messages.
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/ws')
async def ws(websocket: WebSocket):
await websocket.accept()
while True:
msg = await websocket.receive_text()
await websocket.send_text(f'echo: {msg}')Sending JSON
You can exchange structured data with receive_json and send_json instead of raw text.
data = await websocket.receive_json()
await websocket.send_json({'received': data, 'status': 'ok'})Handling Disconnects
Clients drop off. Catch WebSocketDisconnect to clean up resources instead of crashing the handler.
from fastapi import WebSocketDisconnect
try:
while True:
await websocket.receive_text()
except WebSocketDisconnect:
print('client left')A Connection Manager
To broadcast, track active connections in a manager class. Add on connect, remove on disconnect.
class Manager:
def __init__(self):
self.active = []
async def connect(self, ws):
await ws.accept()
self.active.append(ws)
def disconnect(self, ws):
self.active.remove(ws)Broadcasting to Everyone
Loop the active connections and send each one the message. This is the core of a chat room.
async def broadcast(self, message):
for connection in self.active:
await connection.send_text(message)Broadcast Logic in Plain Python
The manager is just list bookkeeping. Here is the connect/disconnect/broadcast flow simulated synchronously.
active = []
def connect(c): active.append(c)
def disconnect(c): active.remove(c)
def broadcast(msg): return [f'{c}<-{msg}' for c in active]
connect('alice'); connect('bob')
print(broadcast('hi'))
disconnect('alice')
print(broadcast('bye'))A Chat Room Endpoint
Combine the pieces: connect, broadcast each received message, and disconnect on drop.
manager = Manager()
@app.websocket('/chat')
async def chat(ws: WebSocket):
await manager.connect(ws)
try:
while True:
text = await ws.receive_text()
await manager.broadcast(text)
except WebSocketDisconnect:
manager.disconnect(ws)Scaling Beyond One Process
An in-memory manager only knows connections on its worker. To broadcast across multiple workers or servers, use a pub/sub backend like Redis to fan out messages.
Security and Limits
Protect WebSocket endpoints:
- Authenticate during the handshake (e.g. token in query or header).
- Validate and size-limit incoming messages.
- Heartbeat/ping to detect dead connections.
Quick Check
Why does an in-memory connection manager fail to broadcast correctly when you run several Uvicorn workers?
Recap
You added real-time communication:
- Accepted WebSocket connections and exchanged text/JSON.
- Handled
WebSocketDisconnectcleanly. - Built a connection manager to broadcast to many clients.
- Learned to scale with Redis pub/sub and to secure connections.
Aprende FastAPI Backend Development Bootcamp con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 21
- Lecciones
- 84
Preguntas frecuentes
¿La lección «WebSockets para comunicación en tiempo real» es gratis?
Sí — el texto completo de «WebSockets para comunicación en tiempo real» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de FastAPI Backend Development Bootcamp, actualiza a CoddyKit PRO. El curso de FastAPI Backend Development Bootcamp incluye 4 lecciones en total.
¿Qué aprenderé en «WebSockets para comunicación en tiempo real»?
Cree funcionalidades en tiempo real en FastAPI con WebSockets: acepte conexiones, intercambie mensajes, difúndalos a varios clientes y gestione las desconexiones correctamente mediante patrones asínc… Practicas FastAPI Backend Development Bootcamp con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar FastAPI Backend Development Bootcamp?
No se requiere experiencia previa. FastAPI Backend Development Bootcamp en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «WebSockets para comunicación en tiempo real»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de FastAPI Backend Development Bootcamp?
Sí. Cada lección de FastAPI Backend Development Bootcamp incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Repaso de async/await en Python
- FastAPI y operaciones asíncronas
- Ejecución de tareas en segundo plano
- WebSockets para comunicación en tiempo real