0Pricing
JavaScript Academy · Lesson

Connection Lifecycle and Errors

Handle open, close, and error events.

The Full Lifecycle

A socket moves through CONNECTINGOPENCLOSINGCLOSED. 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

  1. Opening a WebSocket Connection
  2. Sending and Receiving Messages
  3. Connection Lifecycle and Errors
  4. Reconnection Strategies
← Back to JavaScript Academy