Backend Development 14 min read

Multiple Approaches to Real-Time Data Updates

This article compares three real-time data update techniques—short and long polling, WebSocket, and Server‑Sent Events—explaining their principles, advantages, drawbacks, and providing practical Vue and Node.js code examples to help developers choose the optimal solution for their specific use case.

Zhuanzhuan Tech
Zhuanzhuan Tech
Zhuanzhuan Tech
Multiple Approaches to Real-Time Data Updates

Modern web applications demand real‑time interaction such as instant messaging, live dashboards, and push notifications. This article examines three common solutions—polling, WebSocket, and Server‑Sent Events (SSE)—and discusses when each is appropriate.

1. Polling

Short Polling

Clients repeatedly send HTTP requests at fixed short intervals regardless of data changes. It is easy to implement and works with any browser supporting HTTP, but generates many unnecessary requests, causing repeated TCP handshakes (three‑way handshake, four‑way termination) and potential latency.

Long Polling

Clients send a request that the server holds open until new data is available or a timeout occurs. This reduces useless requests and improves timeliness, yet each held connection consumes server memory and threads, which can become a scalability bottleneck under heavy load.

2. WebSocket

WebSocket establishes a full‑duplex communication channel over a single TCP connection, eliminating the request‑response limitation of HTTP. After an initial handshake (client sends Upgrade: websocket and Connection: Upgrade headers, server replies with status 101 and matching headers), both sides can push data at any time.

The protocol includes connection maintenance via heartbeat frames and a graceful close handshake using a close frame.

<div id="app">
  <input v-model="message" placeholder="输入要发送的消息" />
  <button @click="sendMessage">发送消息</button>
  <div>
    <h3>收到的回复记录:</h3>
    <ul>
      <li v-for="(msg, index) in receivedMessages" :key="msg">{{ msg }}</li>
    </ul>
  </div>
</div>

<script>
  const app = new Vue({
    el: "#app",
    data() { return { message: "", receivedMessages: [], socket: null }; },
    mounted() {
      this.socket = new WebSocket("ws://localhost:3000");
      this.socket.addEventListener("open", () => console.log("已连接到WebSocket服务器"));
      this.socket.addEventListener("message", event => {
        this.receivedMessages.push(event.data);
      });
      this.socket.addEventListener("close", () => console.log("与WebSocket服务器的连接已关闭"));
    },
    methods: {
      sendMessage() {
        if (this.socket.readyState === WebSocket.OPEN) {
          this.socket.send(this.message);
          this.message = "";
        } else {
          console.log("WebSocket连接未就绪,无法发送消息");
        }
      }
    }
  });
</script>

Server‑side example using the ws library:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
const clients = [];

wss.on('connection', ws => {
  console.log('客户端已连接');
  clients.push(ws);

  ws.on('message', message => {
    console.log(`收到客户端消息: ${message}`);
    ws.send(`你发送的消息是:${message}`);
  });

  ws.on('close', () => {
    console.log('客户端已断开连接');
    const index = clients.indexOf(ws);
    if (index > -1) clients.splice(index, 1);
  });
});

setInterval(() => {
  const msg = '这是服务端主动发送的消息,当前时间:' + new Date().toLocaleString();
  clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) client.send(msg);
  });
}, 1000);

console.log('WebSocket服务器已启动,正在监听3000端口...');

3. Server‑Sent Events (SSE)

SSE provides a unidirectional, HTTP‑based push from server to client using the EventSource API. The client initiates a request to an endpoint (e.g., /events ) with headers Content-Type: text/event-stream , Cache-Control: no-cache , and Connection: keep-alive . The server keeps the connection open and periodically sends data formatted as data: ...\n\n .

Client‑side example:

mounted() {
  const source = new EventSource('http://localhost:3000/events');
  source.onmessage = event => {
    const data = JSON.parse(event.data);
    this.message = data.message;
  };
  source.onerror = error => {
    console.log('SSE连接出错:', error);
  };
}

Server‑side example using Express:

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');

  const interval = setInterval(() => {
    const data = `data: { "time": "${new Date().toLocaleString()}" }\n\n`;
    res.write(data);
  }, 3000);

  req.on('close', () => clearInterval(interval));
});

app.listen(port, () => console.log(`服务器运行在 http://localhost:${port}`));

Conclusion

The article outlines the trade‑offs of polling (simple but wasteful), WebSocket (full‑duplex, low latency, higher resource usage), and SSE (simple unidirectional push, limited to text). Developers should select the method that best matches their application's real‑time requirements and infrastructure constraints.

real-timeNode.jsVueWebSocketpollingSSE
Zhuanzhuan Tech
Written by

Zhuanzhuan Tech

A platform for Zhuanzhuan R&D and industry peers to learn and exchange technology, regularly sharing frontline experience and cutting‑edge topics. We welcome practical discussions and sharing; contact waterystone with any questions.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.