Connection Lifecycle and Errors
Handle open, close, and error events.
The Full Lifecycle
A socket moves through CONNECTING → OPEN → CLOSING → CLOSED. Four events map to these transitions: open, message, error, and close.
The onclose Event
onclose fires when the connection ends, cleanly or not. The event carries code, reason, and wasClean.
socket.onclose = (event) => {
console.log("Closed", event.code, event.reason, event.wasClean);
};All lessons in this course
- Opening a WebSocket Connection
- Sending and Receiving Messages
- Connection Lifecycle and Errors
- Reconnection Strategies