단방향 푸시를 위한 Server-Sent Events(SSE)
서버에서 클라이언트로 단방향 데이터 업데이트를 전달할 때 WebSockets의 더 간단한 대안으로 사용할 수 있는 Server-Sent Events(SSE)를 살펴봅니다.
단방향 푸시를 위한 Server-Sent Events(SSE)은(는) CoddyKit의 무료 Real-Time Streaming Systems (WebRTC + Live Data) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Real-Time Streaming Systems (WebRTC + Live Data) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Server-Sent Events
Welcome! In this lesson, we'll explore Server-Sent Events (SSE), a powerful yet simple way for servers to push real-time updates to clients.
Unlike traditional HTTP requests where the client always asks the server for data, SSE allows the server to send data to the client whenever new information is available, without the client needing to constantly poll.
SSE: Simpler Unidirectional Push
You might be familiar with WebSockets for real-time communication. While WebSockets enable full two-way communication, SSE is designed specifically for unidirectional data flow, from the server to the client.
This makes SSE a simpler and often more efficient choice for scenarios where the client only needs to receive updates, not send them back in real-time.
How SSE Connections Work
SSE operates over a standard HTTP connection. The client initiates a regular HTTP request, but the server responds with a special Content-Type: text/event-stream header.
Instead of closing the connection after sending data, the server keeps it open. It then pushes new data to the client whenever updates are ready, effectively streaming events over this single, persistent connection.
Listening with EventSource
On the client-side (typically in a web browser), you use the built-in EventSource API to connect to an SSE stream and listen for incoming events.
Here's a basic JavaScript snippet to connect to an SSE endpoint and log messages:
const eventSource = new EventSource('/stream');
eventSource.onmessage = (event) => {
console.log('New data:', event.data);
// Update your UI here
};
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
eventSource.close(); // Close connection on error
};Building an SSE Server
Let's see how a simple server can send SSE messages. This Node.js example creates an HTTP server that sends the current time every second.
Run this code, then open a browser and navigate to http://localhost:8080 to see the events stream in your console.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// Send a message every second
const intervalId = setInterval(() => {
res.write('data: The time is ' + new Date().toLocaleTimeString() + '\n\n');
}, 1000);
// Clean up on client disconnect
req.on('close', () => {
clearInterval(intervalId);
res.end();
});
}).listen(8080, () => {
console.log('SSE server running on http://localhost:8080');
});Sending Custom SSE Event Types
Beyond the default message event, SSE allows you to define custom event types using the event: field. This helps clients handle different kinds of updates differently.
On the client, you'd use eventSource.addEventListener('myCustomEvent', handler).
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
let counter = 0;
const intervalId = setInterval(() => {
if (counter % 2 === 0) {
res.write('event: heartbeat\n');
res.write('data: Ping! ' + counter + '\n\n');
} else {
res.write('event: update\n');
res.write('data: New data point: ' + Math.random().toFixed(2) + '\n\n');
}
counter++;
}, 2000);
req.on('close', () => {
clearInterval(intervalId);
res.end();
});
}).listen(8080, () => {
console.log('SSE server (custom events) running on http://localhost:8080');
});Automatic Reconnection Magic
One of the most convenient features of EventSource is its built-in automatic reconnection. If the connection drops (due to network issues, server restart, etc.), the browser will automatically attempt to reconnect after a short delay.
You don't need to write any extra code to handle connection failures and retries, making SSE very robust for continuous updates.
Benefits of Using SSE
SSE offers several compelling advantages for server-to-client push:
- Simplicity: Easier to implement than WebSockets for one-way data.
- Built-in Reconnection: Automatic handling of connection drops by
EventSource. - HTTP Compatibility: Works over standard HTTP/HTTPS, compatible with existing infrastructure (proxies, firewalls).
- HTTP/2 Multiplexing: Can share a single connection with other HTTP requests efficiently.
SSE Limitations
While powerful, SSE isn't suitable for all real-time scenarios:
- Unidirectional Only: Only supports server-to-client communication. For client-to-server or true bidirectional, WebSockets are required.
- No Binary Data: Limited to UTF-8 encoded text. You cannot send raw binary data directly via SSE.
- Browser Connection Limits: Browsers typically limit the number of concurrent SSE connections per domain (e.g., 6).
Real-World SSE Examples
SSE shines in applications that need continuous, one-way updates:
- Live Stock Tickers: Continuously pushing price updates to trading dashboards.
- News Feeds: Instant delivery of breaking news or article updates.
- Activity Streams: Real-time notifications (e.g., new emails, social media activity).
- Dashboards: Live updates for monitoring system metrics or user statistics.
SSE Quick Check
Time to test your understanding of Server-Sent Events!
Lesson Summary: SSE
Great job! You've now learned about Server-Sent Events (SSE).
- SSE enables unidirectional, server-to-client data push over a single HTTP connection.
- It's simpler than WebSockets for one-way updates and features automatic reconnection.
- You use the client-side
EventSourceAPI to listen for events. - SSE is perfect for live dashboards, news feeds, and real-time notifications.
Keep exploring how these live data architectures can enhance your applications!
자주 묻는 질문
“단방향 푸시를 위한 Server-Sent Events(SSE)” 강의는 무료인가요?
네 — “단방향 푸시를 위한 Server-Sent Events(SSE)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Real-Time Streaming Systems (WebRTC + Live Data) 강의 전체를 잠금 해제할 수 있습니다. Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 총 4개의 강의가 포함되어 있습니다.
“단방향 푸시를 위한 Server-Sent Events(SSE)”에서 뭘 배우나요?
서버에서 클라이언트로 단방향 데이터 업데이트를 전달할 때 WebSockets의 더 간단한 대안으로 사용할 수 있는 Server-Sent Events(SSE)를 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Real-Time Streaming Systems (WebRTC + Live Data)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Real-Time Streaming Systems (WebRTC + Live Data)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Real-Time Streaming Systems (WebRTC + Live Data)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“단방향 푸시를 위한 Server-Sent Events(SSE)” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Real-Time Streaming Systems (WebRTC + Live Data) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 실시간 데이터와 기존 HTTP 비교
- 양방향 흐름을 위한 WebSockets
- 단방향 푸시를 위한 Server-Sent Events(SSE)
- 롱 폴링과 스트리밍으로의 발전