API WebSocket per la comunicazione in tempo reale
Costruisca connessioni bidirezionali in tempo reale con le API WebSocket di API Gateway. Scopra le route di connessione, disconnessione e messaggistica e come inviare dati ai client.
API WebSocket per la comunicazione in tempo reale è una lezione Serverless Backend with AWS Lambda & API Gateway gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Serverless Backend with AWS Lambda & API Gateway, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Serverless Backend with AWS Lambda & API Gateway include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Domande Frequenti
La lezione «API WebSocket per la comunicazione in tempo reale» è gratuita?
Sì — il testo completo di «API WebSocket per la comunicazione in tempo reale» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Serverless Backend with AWS Lambda & API Gateway, passa a CoddyKit PRO. Il corso Serverless Backend with AWS Lambda & API Gateway include 4 lezioni in totale.
Cosa imparerò in «API WebSocket per la comunicazione in tempo reale»?
Costruisca connessioni bidirezionali in tempo reale con le API WebSocket di API Gateway. Scopra le route di connessione, disconnessione e messaggistica e come inviare dati ai client. Eserciti Serverless Backend with AWS Lambda & API Gateway con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Serverless Backend with AWS Lambda & API Gateway?
Non è richiesta alcuna esperienza precedente. Serverless Backend with AWS Lambda & API Gateway su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «API WebSocket per la comunicazione in tempo reale»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Serverless Backend with AWS Lambda & API Gateway?
Sì. Ogni lezione Serverless Backend with AWS Lambda & API Gateway include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Caching e throttling
- Trasformazioni di richieste e risposte
- Nomi di dominio personalizzati e ottimizzazione edge
- API WebSocket per la comunicazione in tempo reale