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

Connection State

~9 min · browser, readystate

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

readyState 가 가드

OPEN 아닌 connection 에 ws.send() 부르면 InvalidStateError throw. 답은 'try/catch 로 감싸' 가 아니라 'readyState 먼저 확인하거나 open 까지 message queue 해'. readyState 를 '지금 send 가능?' 의 source of truth 로 봐.

네 개 값

0 CONNECTING — handshake 중. 1 OPEN — frame 흘러. 2 CLOSING — close handshake 시작. 3 CLOSED — terminal. WebSocket.OPEN static constant 쓰면 ws.readyState === WebSocket.OPEN 적을 수 있어, 매직 숫자 안 보고.

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;
}
CONNECTING 중 pending-queue·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

위 pending-queue 패턴을 SafeSocket wrapper 클래스로 짜 — connect(), send(), close(). CONNECTING 중 enqueue 한 message 가 open 시 순서대로 flush 되는지, CLOSED 후 send 가 명확한 에러로 throw 되는지 테스트.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.