mason
mason-log.

mason

mason.

안녕하세요. mason 입니다.

network

WebSocket.

HTTP upgrade, 양방향 통신, Socket.io vs native, 재연결 패턴

WebSocket은 HTTP handshake 후 양방향, 지속 연결로 실시간 메시지를 주고받는 프로토콜입니다.

🔌 연결 과정

WebSocket 업그레이드와 양방향 프레임

  1. Client Upgrade: websocket HTTP request
  2. Server 101 Switching Protocols
  3. Frame 기반 full-duplex 통신
  4. Close handshake

⚖️ vs HTTP polling

PollingWebSocket
연결반복 HTTP한 connection 유지
latency높음낮음
서버 부하요청마다 overheadconnection 유지 비용
용도간헐적 업데이트채팅, live score, collaborative

💻 프론트엔드

const ws = new WebSocket('wss://api.example.com/ws');
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe' }));
ws.onmessage = (e) => console.log(JSON.parse(e.data));
ws.onclose = () => reconnectWithBackoff();
  • wss:// (TLS) 필수 (mixed content)
  • heartbeat/ping, exponential backoff 재연결
  • React: useEffect cleanup에서 ws.close()

📚 Socket.io / libraries

  • auto reconnect, fallback long-polling
  • room, namespace abstraction
  • native WS로 충분하면 dependency 줄이기

🔗 참고 자료