C.W.K.
Stream
Lesson 04 of 08 · published

Connection States

~9 min · browser, readystate

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

readyState is your guard

Calling ws.send() on a connection that is not OPEN throws a InvalidStateError. The fix is not "wrap in try/catch" — it is "check readyState first, or queue the message until open fires." Treat readyState as the source of truth for "can I send right now?"

The four values

0 CONNECTING — handshake in flight. 1 OPEN — frames flow. 2 CLOSING — close handshake started. 3 CLOSED — terminal. The WebSocket.OPEN static constant lets you write ws.readyState === WebSocket.OPEN and skip the magic numbers.

Code

Safe send wrapper·javascript
function safeSend(ws, payload) {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(payload);
    return true;
  }
  console.warn('send dropped, state =',
    ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'][ws.readyState]);
  return false;
}
Pending-queue while CONNECTING·javascript
const pending = [];

function send(ws, payload) {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(payload);
  } else if (ws.readyState === WebSocket.CONNECTING) {
    pending.push(payload);
  } else {
    throw new Error('socket is closing/closed');
  }
}

ws.addEventListener('open', () => {
  while (pending.length) ws.send(pending.shift());
});

External links

Exercise

Write the pending-queue pattern above into a SafeSocket wrapper class with connect(), send(), and close(). Test that messages enqueued during CONNECTING flush in order on open, and that messages sent after CLOSED throw a clear error.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.