APIs WebSocket para comunicação em tempo real
Crie conexões bidirecionais em tempo real com as APIs WebSocket do API Gateway. Aprenda as rotas de conexão, desconexão e mensagens, além de como enviar dados de volta aos clientes.
APIs WebSocket para comunicação em tempo real é uma aula grátis de Serverless Backend with AWS Lambda & API Gateway no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Serverless Backend with AWS Lambda & API Gateway, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Serverless Backend with AWS Lambda & API Gateway inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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
Perguntas Frequentes
A aula “APIs WebSocket para comunicação em tempo real” é grátis?
Sim — o texto completo de “APIs WebSocket para comunicação em tempo real” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Serverless Backend with AWS Lambda & API Gateway, atualize para CoddyKit PRO. O curso de Serverless Backend with AWS Lambda & API Gateway inclui 4 aulas no total.
O que vou aprender em “APIs WebSocket para comunicação em tempo real”?
Crie conexões bidirecionais em tempo real com as APIs WebSocket do API Gateway. Aprenda as rotas de conexão, desconexão e mensagens, além de como enviar dados de volta aos clientes. Você pratica Serverless Backend with AWS Lambda & API Gateway com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Serverless Backend with AWS Lambda & API Gateway?
Nenhuma experiência prévia é necessária. Serverless Backend with AWS Lambda & API Gateway no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “APIs WebSocket para comunicação em tempo real”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Serverless Backend with AWS Lambda & API Gateway?
Sim. Cada aula de Serverless Backend with AWS Lambda & API Gateway inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Armazenamento em cache e limitação de tráfego
- Transformações de solicitações e respostas
- Nomes de domínio personalizados e otimização de borda
- APIs WebSocket para comunicação em tempo real