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

Connection 닫기

~10 min · browser, close-codes

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

close(code, reason)

ws.close() 부르면 close handshake 시작 — 브라우저가 close frame 보내고, 서버가 close frame 으로 답하고, 밑의 TCP socket 닫혀. close code 와 reason 옵션으로 넘겨. reason 은 UTF-8 string, max 123 byte — 'session expired' 정도엔 충분하고 close frame 가볍게 유지하는 데 충분히 짧아.

Application close code (4000-4999)

4000-4999 범위는 application-defined code 용. protocol 에 stable 한 거 몇 개 골라 — 4001 unauthorized, 4029 too many connections, 4040 room not found — 그러면 클라가 깔끔히 분기 가능. application logic 에서 1xxx code (1001 이나 1011 같은 거) 안 쓰는 게 좋아; RFC 의미 있어.

wasClean 이 진실 알려줘

close 이벤트의 wasClean boolean. true 면 제대로 close handshake 완료; code 의미 있어. false 면 connection 죽음 — code 는 보통 1006 이고 reason 은 비어있어.

Code

Close with reason·javascript
// Normal user-initiated logout
ws.close(1000, 'user logged out');

// Application-defined: "your token has expired"
ws.close(4001, 'token expired');

// React to close codes on the listener side
ws.addEventListener('close', (e) => {
  if (!e.wasClean) {
    console.warn('connection lost — schedule reconnect');
    return scheduleReconnect();
  }
  switch (e.code) {
    case 1000: return console.log('clean close');
    case 1001: return console.log('server going away');
    case 4001: return redirectToLogin();
    case 4029: return showRateLimitToast();
    default:   return console.warn('unexpected close', e.code, e.reason);
  }
});

External links

Exercise

가상의 chat 앱에 5행 close-code 표 정의: 1000 normal, 4001 unauthorized, 4029 rate limited, 4040 room not found, 4503 server overloaded. 클라에 switch 짜서 각각 다른 toast 만들어. 서버 쪽에서 각 trigger 해서 UI 가 옳게 반응하는지 확인.

Progress

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

댓글 0

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

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