SSE(Server-Sent Events)는 서버에서 클라이언트로 단방향 실시간 스트리밍을 구현하는 HTTP 기반 프로토콜이다. WebSocket보다 단순하며 HTTP/2와 잘 통합되고, 자동 재연결을 기본 지원한다.
동작 방식
클라이언트 서버
|--- GET /events →|
| |
|← data: hello
|
|← data: world
|
| (연결 유지) |
|← data: ...
|
서버 구현 (Node.js)
javascript
// Express SSE 엔드포인트
app.get('/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// 초기 연결
res.write('data: {"type": "connected"}
');
// 주기적 데이터 전송
const interval = setInterval(() => {
const data = { time: new Date().toISOString(), value: Math.random() };
res.write(`data: ${JSON.stringify(data)}
`);
}, 1000);
// 이벤트 타입 지정
res.write('event: priceUpdate
');
res.write('data: {"price": 42000}
');
// 연결 종료 처리
req.on('close', () => {
clearInterval(interval);
res.end();
});
});
클라이언트 구현
javascript
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
};
eventSource.addEventListener('priceUpdate', (event) => {
const { price } = JSON.parse(event.data);
updatePrice(price);
});
eventSource.onerror = () => {
// 자동 재연결 (브라우저 기본 동작)
};
| SSE | WebSocket | Long Polling |
|---|
| 방향 | 단방향 (서버→클라이언트) | 양방향 | 단방향 |
| 프로토콜 | HTTP | WS | HTTP |
| 자동 재연결 | 지원 | 미지원 | 구현 필요 |
| 적합한 경우 | 피드, 알림, 실시간 로그 | 채팅, 게임 | 레거시 지원 |
관련 개념