• Our general request is made by the client to the server, and then the server to return the data back, he lacks a real time
  • Suppose we now have a requirement to actively push data to the client when some data changes on the server. What should we do?
  • I’ve written examples for each one, so you can look at them
  • It is recommended that everyone look at the browserNetworkConvenient for observation
  • Let’s take a look at push technology

The HTTP protocol

  • Let’s start with the -HTTP that we use in general
  • HTTP is a hypertext data transfer protocol, which is mainly used to define how data is transferred, and the format of packets
  • It was designed in a single mode/temporary mode (after completing the response request, the connection is disconnected, no longer real-time push, need to request again)
  • In fact, when the server returns a page, the client looks at the page, and we don’t want to pop up something inexplicably while looking at the page or suddenly change the text we’re looking at
  • Request/response pattern
    • The client must first send the request, and the server must respond to the request
      • Client => Server (request)
      • Server => Client (response)
    • Problem: The server cannot push data to the client in a timely manner
  • Stateless mode
    • HTTP does not save (not persist, not remember) the client for each request
    • Problem: The server cannot tell whether the current client request has been processed or authenticated
  • The goal is to reduce server overhead

Real-time transport requirements and dealing with HTTP protocol singleness

  • With more and more people accessing the Internet, different requirements have emerged. At this time, we hope to have certain requirements on the real-time transmission, but the HTTP protocol has been set. What should we do at this time?


  • This operation is very simple, just keep pressing your refresh, we can manually complete the polling
  • In terms of implementation: the client periodically sends Ajax requests to the server, and the server immediately returns the response information and closes the connection, regardless of whether there is any response data
  • Advantages: Very simple implementation
  • Disadvantages: wasted bandwidth and server resources, and delays in responding to new data
  • Application scenario: Small application scenarios
  • demo – node app.js

Long polling

  • Similar to simple polling, except that the server does not respond immediately if no new data is returned, but suspends until data is available or is about to time out
  • Advantages: the implementation is not complex, and relatively polling, saving bandwidth
  • Disadvantages: there is still the problem of occupying server resources, although the timeliness is higher than polling, but it will be suspended in the server when there is no data, so it will always occupy server resources, less processing capacity
  • Applications: Some of the early applications that had some timeliness requirements: Web IM chat
  • demo – node app.js
  • The demo repeatedly judged that oldData and Data were just a simulation, and there must be trigger conditions in the actual application, such as: chat, others sent new messages, etc

Server Send Event (SSE) Server push

  • A client retrieving new data usually needs to send a request to the server, which is the data requested from the server. With the server-sent event, the server can push data and information to our clients at any time. The information that is pushed in can be processed on the client as Events + data
  • It is a one-way communication of events and data sent from the server to the client based on WebSocket protocol
  • HTML5 server-sent events allow web pages to receive updates from the server
  • Features: Unidirectional communication – After the client and server send requests to connect, the server can send events and data to the client at any time

The client

  • Use the EventSource class interface to complete the request
// /upData is the URL to get the data
const source = new EventSource("/upData");

// listen 'ping' (events defined by the server), which receives events when pushed by the server
source.addEventListener('ping'.e= > {
    div.innerHTML =;

// Close the connection
Copy the code

The service side

  • Specified Settings are required on the server

Header information

Copy the code

Return data format

// Event indicates that the client receives events, and data indicates that the client receives data
res.write(`event: ping\ndata: {a: ${data}}\n\n`);

// When the client is disconnected
req.connection.addListener('close'.() = >{});Copy the code

See apis and examples

  • EventSource
  • Server-sent events
  • demonode app.js


  • WebSocket is a protocol that HTML5 is beginning to provide for full duplex communication over a single connection
  • WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client
  • The client and server only need to complete a handshake, the two can directly create a persistent connection and two-way data transfer
  • In the handshake phase, the HTTP protocol is adopted, so it is not easy to mask the handshake and can pass various HTTP proxy servers
  • I mainly use the WebSocket library –
  • Here is a brief introduction to the basic use, API is also much, there is a need or check bai ~

The installation

npm install
Copy the code

The service side


// Server is http.createServer, and the second parameter options is used to configure the socket
const io = require('')(server);
Copy the code


  • This is similar to native, except that the first argument to socket. IO requires a raw HTTP object, so we’ll do that here
  • This is equivalent to passing koA-wrapped methods into native HTTP objects
const Koa = require('koa');
const app = new Koa();
const server = require('http').createServer(app.callback());
const io = require('')(server, { });
Copy the code
  • Server connection
io.on('connection'.socket= >{}// The client responds after the connection
Copy the code

The client

  • io()Internal parameters can be configuration items and are used to pair with server information
<! -- This link will be made directly to the server, equivalent to a handshake request -->
<script src="/"></script>
Copy the code
const socket = io('/'); // Request that the connection be upgraded to webSocket protocol - connection
Copy the code

Sending and receiving

  • The client and server methods are the sameemitSend a message,onReceives the message

socket.on('hello'.data= > {
Copy the code
  • Server broadcast – send to others
socket.broadcast.emit('hello'.'Welcome, everybody.');
Copy the code

See apis and examples

  • Simple chat room demo– native:node app1.js; Koa:node app2.js