0Pricing
WebSockets & Realtime Systems Programming · 课时

轮询、长轮询与 SSE

比较传统的轮询和长轮询方法与用于推送数据的服务器发送事件。

轮询、长轮询与 SSE 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「轮询、长轮询与 SSE」课时是免费的吗?

是的 — 「轮询、长轮询与 SSE」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

「轮询、长轮询与 SSE」这节课中我会学到什么?

比较传统的轮询和长轮询方法与用于推送数据的服务器发送事件。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Realtime Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「轮询、长轮询与 SSE」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?

能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 网络通信的演进
  2. 轮询、长轮询与 SSE
  3. WebSockets 简介:开启新时代
  4. 选择合适的实时技术
← 返回 WebSockets & Realtime Systems Programming