WebSockets & Realtime Systems Programming · Lektion

Polling, Long Polling und SSE

Vergleichen Sie herkömmliche Methoden wie Polling und Long Polling mit Server-Sent Events zum Übertragen von Daten.

Lektion 2 von 412 Schritte

Polling, Long Polling und SSE ist eine kostenlose WebSockets & Realtime Systems Programming-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des WebSockets & Realtime Systems Programming-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der WebSockets & Realtime Systems Programming-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

HTTP's Realtime Challenge

HTTP is stateless and unidirectional: the client asks, the server answers once. For live chat or tickers, constant asking or waiting is inefficient.

Introducing Polling

Polling is the simplest pseudo-realtime trick: the client asks the server for new data on a fixed interval, getting updates or an empty reply each time.

Polling Code Example

Here's a JavaScript client that polls a server every 2 seconds for updates — open your console to watch it fire.

<!DOCTYPE html>
<html>
<head>
  <title>Polling Example</title>
</head>
<body>
  <h1>Polling Status: <span id="status">Waiting...</span></h1>
  <script>
    function fetchData() {
      // In a real app, this would be a server endpoint
      fetch('https://jsonplaceholder.typicode.com/todos/1') 
        .then(response => response.json())
        .then(data => {
          const statusElement = document.getElementById('status');
          statusElement.innerText = `Update at ${new Date().toLocaleTimeString()}`; 
          console.log('Polled:', data.title);
        })
        .catch(error => console.error('Polling error:', error));
    }

    // Poll every 2 seconds (2000 milliseconds)
    setInterval(fetchData, 2000);
    fetchData(); // Initial fetch to start
  </script>
</body>
</html>

Polling's Inefficiency

Polling is wasteful: high latency between polls, many empty responses burning resources, and poor scaling when many clients poll often.

Enter Long Polling

Long polling is smarter: instead of replying empty, the server holds the request open until data is ready or it times out, then the client reconnects.

How Long Polling Works

The long polling cycle: client requests, server waits for data or timeout, server responds and closes, client immediately re-requests to restart.

Long Polling Client Logic

Here's the long polling client pattern: it processes each response, then immediately reopens the connection (retrying after a delay on error).

function longPoll() {
  console.log('Long polling for updates...');
  fetch('/api/longpoll') // Imagine this endpoint holds the request
    .then(response => response.json())
    .then(data => {
      if (data && data.message) {
        console.log('Received update:', data.message);
        // In a real app, update UI here
      } else {
        console.log('No new data, server likely timed out or sent empty.');
      }
      longPoll(); // Immediately send a new request
    })
    .catch(error => {
      console.error('Long polling error:', error);
      // Retry after a delay on error to prevent flooding
      setTimeout(longPoll, 3000); 
    });
}

longPoll(); // Start the long polling process

Long Polling's Pros & Cons

Long polling cuts latency and request count versus plain polling, but it still rides the request-response model — each update sets up and tears down a connection.

Server-Sent Events (SSE)

Server-Sent Events (SSE) give true server push over one long-lived HTTP connection. It's one-way (server to client) — perfect for feeds, tickers, notifications.

SSE Client Example

The native EventSource API makes subscribing to an SSE stream easy — the connection stays open until you close it or an error hits.

<!DOCTYPE html>
<html>
<head>
  <title>SSE Example</title>
</head>
<body>
  <h1>SSE Updates:</h1>
  <ul id="events"></ul>
  <script>
    // Imagine a server at /sse-stream sending events
    const eventSource = new EventSource('https://example.com/sse-stream'); // Replace with a real SSE endpoint

    eventSource.onopen = () => {
      console.log('SSE connection opened.');
      const listItem = document.createElement('li');
      listItem.textContent = `Connection opened at ${new Date().toLocaleTimeString()}`;
      document.getElementById('events').appendChild(listItem);
    };

    eventSource.onmessage = (event) => {
      const listItem = document.createElement('li');
      listItem.textContent = `New message: ${event.data}`;
      document.getElementById('events').appendChild(listItem);
      console.log('Received SSE message:', event.data);
    };

    eventSource.onerror = (error) => {
      console.error('SSE Error:', error);
      const listItem = document.createElement('li');
      listItem.textContent = `Error: ${error.message || 'Unknown'}`;
      document.getElementById('events').appendChild(listItem);
      eventSource.close(); // Close connection on error
    };

    // You can also listen for custom named events:
    // eventSource.addEventListener('myCustomEvent', (event) => {
    //   console.log('Custom event data:', event.data);
    // });
  </script>
</body>
</html>

Quick Check: Compare Methods

Which of the following statements about Polling, Long Polling, and Server-Sent Events (SSE) are true?

Recap: Unidirectional Push

Recap: polling repeatedly asks (simple but wasteful), long polling holds the request open, and SSE pushes one-way over a persistent connection.

Kostenlos starten

Lerne WebSockets & Realtime Systems Programming mit einem KI-Tutor — kostenlos

Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.

Kurse
12
Lektionen
47

Häufig gestellte Fragen

Ist die Lektion „Polling, Long Polling und SSE“ kostenlos?

Ja — der vollständige Text von „Polling, Long Polling und SSE“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des WebSockets & Realtime Systems Programming-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der WebSockets & Realtime Systems Programming-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Polling, Long Polling und SSE“?

Vergleichen Sie herkömmliche Methoden wie Polling und Long Polling mit Server-Sent Events zum Übertragen von Daten. Du übst WebSockets & Realtime Systems Programming mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um WebSockets & Realtime Systems Programming zu starten?

Keine Vorkenntnisse erforderlich. WebSockets & Realtime Systems Programming auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.

Wie lange dauert die Lektion „Polling, Long Polling und SSE“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser WebSockets & Realtime Systems Programming-Lektion Code schreiben und ausführen?

Ja. Jede WebSockets & Realtime Systems Programming-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Die Entwicklung der Webkommunikation
  2. Polling, Long Polling und SSE
  3. WebSockets – eine neue Ära
  4. Die passende Echtzeittechnologie auswählen
← Zurück zu WebSockets & Realtime Systems Programming