API WebSocket para comunicación en tiempo real
Construya conexiones bidireccionales en tiempo real con las API WebSocket de API Gateway. Aprenda las rutas de conexión, desconexión y mensajes, y cómo enviar datos de vuelta a los clientes.
API WebSocket para comunicación en tiempo real es una lección gratuita de Serverless Backend with AWS Lambda & API Gateway 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 Serverless Backend with AWS Lambda & API Gateway, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why WebSockets?
REST APIs are request/response — the server cannot push. For chat, live dashboards, or notifications you need a persistent two-way channel. API Gateway WebSocket APIs provide exactly that.
The Three Built-in Routes
A WebSocket API has special routes:
$connectwhen a client connects$disconnectwhen it leaves$defaultfor unmatched messages
Route Selection Expression
Custom routes are chosen by a route selection expression, usually a field in the incoming JSON such as $request.body.action.
{
"action": "sendMessage",
"data": "hello"
}Handling $connect
The $connect handler receives a unique connectionId. Store it (e.g. in DynamoDB) so you can message that client later.
exports.handler = async (event) => {
const id = event.requestContext.connectionId;
await save(id);
return { statusCode: 200 };
};Handling $disconnect
On disconnect, remove the stored connectionId so you do not try to message a dead client.
exports.handler = async (event) => {
await remove(event.requestContext.connectionId);
return { statusCode: 200 };
};Pushing Messages to a Client
To send data back, call the management API with the target connectionId.
const api = new ApiGatewayManagementApi({ endpoint });
await api.postToConnection({
ConnectionId: id,
Data: JSON.stringify({ msg: "hi" })
});Broadcasting to Many Clients
To broadcast, loop over all stored connectionIds and post to each. Remove any that return a 410 Gone status — those clients have disconnected.
Authorizing Connections
Attach a Lambda authorizer to the $connect route to validate a token before the connection is accepted, rejecting unauthorized clients up front.
Connection Lifetime and Limits
WebSocket connections last up to 2 hours, with a 10-minute idle timeout. Clients should reconnect when dropped, and you should handle stale connectionIds gracefully.
Pricing Model
You pay for messages transferred and for connection-minutes, not for idle request count. This makes WebSocket APIs cost-effective for bursty real-time traffic.
When to Use WebSockets
Reach for WebSocket APIs when you need:
- Live chat or collaboration
- Real-time dashboards
- Server-initiated notifications
For simple request/response, stick with REST or HTTP APIs.
Quick Check
Test your WebSocket API knowledge.
Recap
You learned real-time APIs:
- WebSocket APIs add two-way communication
$connect,$disconnect,$defaultplus custom routes- Store connectionIds and push via postToConnection
- Authorize on $connect; handle stale connections
Preguntas frecuentes
¿La lección «API WebSocket para comunicación en tiempo real» es gratis?
Sí — el texto completo de «API WebSocket 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 Serverless Backend with AWS Lambda & API Gateway, actualiza a CoddyKit PRO. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.
¿Qué aprenderé en «API WebSocket para comunicación en tiempo real»?
Construya conexiones bidireccionales en tiempo real con las API WebSocket de API Gateway. Aprenda las rutas de conexión, desconexión y mensajes, y cómo enviar datos de vuelta a los clientes. Practicas Serverless Backend with AWS Lambda & API Gateway 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 Serverless Backend with AWS Lambda & API Gateway?
No se requiere experiencia previa. Serverless Backend with AWS Lambda & API Gateway 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 «API WebSocket 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 Serverless Backend with AWS Lambda & API Gateway?
Sí. Cada lección de Serverless Backend with AWS Lambda & API Gateway 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
- Almacenamiento en caché y limitación de tráfico
- Transformaciones de solicitudes y respuestas
- Nombres de dominio personalizados y optimización perimetral
- API WebSocket para comunicación en tiempo real