0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · درس

الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه

استكشف الأحداث المرسلة من الخادم (SSE) كبديل أبسط لـ WebSockets لدفع تحديثات البيانات أحادية الاتجاه من الخادم إلى العميل.

الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه درس مجاني في Real-Time Streaming Systems (WebRTC + Live Data) على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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 EventSource API 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!

الأسئلة الشائعة

هل درس «الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه» مجاني؟

نعم — نص درس «الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Real-Time Streaming Systems (WebRTC + Live Data)، انتقل إلى CoddyKit PRO. تتضمن دورة Real-Time Streaming Systems (WebRTC + Live Data) 4 دروس في المجموع.

ماذا ستتعلم في «الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه»؟

استكشف الأحداث المرسلة من الخادم (SSE) كبديل أبسط لـ WebSockets لدفع تحديثات البيانات أحادية الاتجاه من الخادم إلى العميل. تتمرن على Real-Time Streaming Systems (WebRTC + Live Data) مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Real-Time Streaming Systems (WebRTC + Live Data)؟

لا تُشترط خبرة سابقة. Real-Time Streaming Systems (WebRTC + Live Data) على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Real-Time Streaming Systems (WebRTC + Live Data) هذا؟

نعم. كل درس في Real-Time Streaming Systems (WebRTC + Live Data) يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. البيانات الفورية مقابل HTTP التقليدي
  2. WebSockets للتدفق ثنائي الاتجاه
  3. الأحداث المرسلة من الخادم (SSE) للدفع أحادي الاتجاه
  4. الاستطلاع الطويل والتطور نحو البث
← العودة إلى Real-Time Streaming Systems (WebRTC + Live Data)