WebSockets & Realtime Systems Programming · Lezione

Polling, long polling e SSE

Confronti i metodi tradizionali, come polling e long polling, con i Server-Sent Events per l'invio dei dati.

Lezione 2 di 412 passaggi

Polling, long polling e SSE è una lezione WebSockets & Realtime Systems Programming gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento WebSockets & Realtime Systems Programming, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso WebSockets & Realtime Systems Programming include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Gratis per iniziare

Impara WebSockets & Realtime Systems Programming con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
47

Domande Frequenti

La lezione «Polling, long polling e SSE» è gratuita?

Sì — il testo completo di «Polling, long polling e SSE» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso WebSockets & Realtime Systems Programming, passa a CoddyKit PRO. Il corso WebSockets & Realtime Systems Programming include 4 lezioni in totale.

Cosa imparerò in «Polling, long polling e SSE»?

Confronti i metodi tradizionali, come polling e long polling, con i Server-Sent Events per l'invio dei dati. Eserciti WebSockets & Realtime Systems Programming con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare WebSockets & Realtime Systems Programming?

Non è richiesta alcuna esperienza precedente. WebSockets & Realtime Systems Programming su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Polling, long polling e SSE»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione WebSockets & Realtime Systems Programming?

Sì. Ogni lezione WebSockets & Realtime Systems Programming include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. L'evoluzione della comunicazione sul Web
  2. Polling, long polling e SSE
  3. Introduzione ai WebSocket: una nuova era
  4. Scegliere la tecnologia realtime giusta
← Torna a WebSockets & Realtime Systems Programming