0Pricing
WebSockets & Realtime Systems Programming · 강의

Server-Sent Events(SSE) 다시 보기

단방향 서버-클라이언트 스트리밍에 SSE가 적합한지 다시 검토하고, 특정 사용 사례에서 WebSockets와 비교합니다.

Server-Sent Events(SSE) 다시 보기은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Revisiting Server-Sent Events

Welcome back to Server-Sent Events (SSE)! While we briefly touched upon SSE earlier, this lesson dives deeper into its unique strengths and optimal use cases in modern realtime web development.

In a world dominated by WebSockets for full-duplex communication, SSE holds its ground for specific scenarios where a simpler, unidirectional stream is all you need.

SSE: Server-to-Client Only

The fundamental principle of SSE is its unidirectional nature. It allows a server to push updates to a client over a single, persistent HTTP connection.

  • Data flows only from the server to the client.
  • Clients cannot send messages back to the server using the same SSE connection.
  • This simplicity makes it ideal for broadcast-style updates.

Why Choose SSE? Key Benefits

SSE offers several advantages, especially when compared to constantly polling a server:

  • Simplicity: Built on HTTP, easier to implement than WebSockets for simple pushes.
  • Automatic Reconnection: Browsers handle reconnects automatically if the connection drops.
  • Event IDs: Built-in mechanism to track the last received event, preventing data loss.
  • Browser Native: Uses the standard EventSource API, no complex libraries needed.

SSE vs. WebSockets: Unidirectional vs. Bidirectional

This is the crucial distinction:

  • SSE: Best for scenarios where the client only needs to receive updates (e.g., news feeds, stock prices). It's like a radio broadcast.
  • WebSockets: Essential for interactive applications where clients and servers need to send and receive messages freely (e.g., chat apps, online gaming). It's like a phone call.

Choosing between them depends purely on your application's communication needs.

Use Case: Realtime Data Feeds

Consider applications that display live, constantly updating information. These are perfect candidates for SSE:

  • Stock Tickers: Displaying real-time changes in stock prices.
  • News Feeds: Pushing new headlines or articles as they're published.
  • Sports Scores: Instant updates on game scores or events.

The client just listens; it doesn't need to send anything back to initiate updates.

Use Case: Notifications and Progress

Another strong use case for SSE is delivering non-interactive notifications or tracking progress:

  • User Notifications: "You have a new message!" or "Your friend liked your post."
  • Background Job Progress: Showing the status of a long-running server task (e.g., "File upload 50% complete").

These scenarios benefit from the server pushing updates without client request, and the client doesn't need to respond.

Building an SSE Server (Node.js)

Here's a simple Node.js example using Express to create an SSE endpoint. Notice the Content-Type header, crucial for SSE.

Try running this example:

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/events', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.flushHeaders(); // Flush headers to establish connection

  let counter = 0;
  const intervalId = setInterval(() => {
    counter++;
    res.write(`data: Server time: ${new Date().toLocaleTimeString()}, count: ${counter}\n\n`);
    if (counter >= 5) {
      res.end(); // End connection after 5 messages
      clearInterval(intervalId);
    }
  }, 1000);

  req.on('close', () => {
    console.log('Client disconnected');
    clearInterval(intervalId);
  });
});

app.get('/', (req, res) => {
  res.send('<p>Go to <a href="/events">/events</a> to see SSE stream.</p><script>const eventSource = new EventSource("/events"); eventSource.onmessage = function(event) { console.log(event.data); document.body.innerHTML += `<p>${event.data}</p>`; }; eventSource.onerror = function(error) { console.error("SSE Error:", error); };</script>');
});

app.listen(PORT, () => {
  console.log(`SSE server listening on port ${PORT}`);
});

Consuming SSE in the Browser

On the client side, consuming SSE is straightforward using the native EventSource API. No special libraries are needed!

This JavaScript snippet shows how to connect and handle incoming messages:

const eventSource = new EventSource('/my-sse-endpoint');

eventSource.onmessage = function(event) {
  console.log("Data received:", event.data);
  // event.data contains the message payload
  // event.lastEventId contains the ID of the last event
};

eventSource.addEventListener('myCustomEvent', function(event) {
  console.log("Custom event received:", event.data);
});

eventSource.onopen = function() {
  console.log("SSE connection established.");
};

eventSource.onerror = function() {
  console.error("SSE connection error or closed.");
  if (eventSource.readyState === EventSource.CLOSED) {
    console.log("Connection closed. Browser will try to reconnect.");
  }
};

// To manually close the connection
// eventSource.close();

Understanding SSE's Limitations

While powerful for its niche, SSE isn't a silver bullet. Be aware of its limitations:

  • No Bidirectional Communication: Clients cannot send data back to the server over the SSE connection. For that, you need a separate HTTP request or WebSockets.
  • Text-Only Data: SSE natively supports only UTF-8 encoded text data. Binary data requires encoding (e.g., Base64), adding overhead.
  • Connection Limits: Browsers typically limit the number of concurrent HTTP connections (usually 6-8 per domain), which applies to SSE.

Event IDs and Automatic Reconnects

EventSource offers built-in features for robustness:

  • Last-Event-ID: If the connection drops, the browser automatically includes the Last-Event-ID header in the reconnection request. The server can use this to send only missed events.
  • Automatic Reconnection: The browser automatically attempts to reconnect to the SSE endpoint if the connection is lost. The server can also suggest a retry interval using retry: field.

These features greatly simplify error handling compared to polling.

SSE Quick Check

Considering the core functionalities, which statement best describes Server-Sent Events (SSE)?

SSE Revisited: Recap

In this lesson, we revisited Server-Sent Events (SSE), understanding its distinct role in realtime web applications.

  • SSE is ideal for unidirectional server-to-client streaming, perfect for live feeds and notifications.
  • It's simpler to implement than WebSockets for push-only scenarios, offering automatic reconnection and event IDs.
  • Remember its limitations: no client-to-server communication and text-only data.

Choose SSE when you only need the server to broadcast updates to clients, keeping your architecture lean and efficient.

자주 묻는 질문

“Server-Sent Events(SSE) 다시 보기” 강의는 무료인가요?

네 — “Server-Sent Events(SSE) 다시 보기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“Server-Sent Events(SSE) 다시 보기”에서 뭘 배우나요?

단방향 서버-클라이언트 스트리밍에 SSE가 적합한지 다시 검토하고, 특정 사용 사례에서 WebSockets와 비교합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Server-Sent Events(SSE) 다시 보기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WebTransport와 WebRTC 데이터 채널
  2. Server-Sent Events(SSE) 다시 보기
  3. 실시간 웹 API의 미래
  4. 엣지 컴퓨팅과 네트워크 엣지의 실시간 처리
← WebSockets & Realtime Systems Programming(으)로 돌아가기