network
WebSocket.
HTTP upgrade, 양방향 통신, Socket.io vs native, 재연결 패턴
WebSocket은 HTTP handshake 후 양방향, 지속 연결로 실시간 메시지를 주고받는 프로토콜입니다.
🔌 연결 과정
- Client
Upgrade: websocketHTTP request - Server
101 Switching Protocols - Frame 기반 full-duplex 통신
- Close handshake
⚖️ vs HTTP polling
| Polling | WebSocket | |
|---|---|---|
| 연결 | 반복 HTTP | 한 connection 유지 |
| latency | 높음 | 낮음 |
| 서버 부하 | 요청마다 overhead | connection 유지 비용 |
| 용도 | 간헐적 업데이트 | 채팅, 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:
useEffectcleanup에서ws.close()
📚 Socket.io / libraries
- auto reconnect, fallback long-polling
- room, namespace abstraction
- native WS로 충분하면 dependency 줄이기
🔗 참고 자료
- MDN: WebSocket — 브라우저 WebSocket API를 설명한다.
- RFC 6455: The WebSocket Protocol — WebSocket 프로토콜의 IETF 표준이다.
- WHATWG WebSockets Living Standard — WebSocket 클라이언트 측 Living Standard다.
