I. WebSocket understanding

  1. Concept: WebSocket is a protocol that HTML5 is beginning to provide for full-duplex communication over a single TCP connection.

  2. Features: WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

  3. Flow: In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

  4. For now: Ajax polling is used by many websites to implement push technology. Polling is when the browser makes an HTTP request to the server at a specific time interval (e.g., every 1 second), and the server returns the latest data to the client’s browser. This traditional pattern has obvious disadvantages, namely, the browser needs to make continuous requests to the server. However, HTTP requests may contain long headers, in which only a small portion of the data is really valid, which obviously wastes a lot of bandwidth and other resources.

  5. Advantages: WebSocket protocol defined by HTML5, can better save server resources and bandwidth, and can be more real-time communication.


2. WebSocket attributes

  1. WebSocket object
let ws = new WebSocket('ws://localhost:3000') // Create a WebSocket object
Copy the code


  1. WebSocket object properties:
attribute describe
ws.readyState The read-only property readyState represents the connection state and can be the following values:

0 – Indicates that the connection is not established.

1 – Indicates that the connection is established and communication can be performed.

2 – Indicates that the connection is being closed.

3 – Indicates that the connection is closed or cannot be opened.


  1. WebSocket object events:
The event Event handler describe
open ws.onopen Triggered when the connection is established
message ws.onmessage Triggered when the client receives data from the server
error ws.onerror Triggered when a communication error occurs
close ws.onclose Triggered when the connection is closed


  1. WebSocket object methods:
methods describe
ws.send() Use the connection to send data
ws.close() Close the connection


Three, WebSocket use


// Create a WebSocket object
let ws = new WebSocket('ws://localhost:3000')
/ / timer
let timer;

// Listen on
ws.onopen = webSocketOpen;
// Listen exception
ws.onerror = webSocketError;
// Listen for messages
ws.onmessage = webSocketMessage;
// The listener is closed
ws.onclose = webSocketClose;


function webSocketOpen() {
    console.log('Connection successful')
    start()
},

function webSocketError() {
    console.log('Connection is abnormal, please refresh the page and try again')},function webSocketMessage(e) {
    console.log('Received message:${e.data}`)},function webSocketClose() {
    console.log('Connection closed')
    clearInterval(timer)
},

// Send heartbeat, because long time does not send message, will be broken
function start() {
  clearInterval(timer)
  timer = setInterval(() = > {
    let date = new Date()
    ws.send('sends the heartbeat to the back end${date}`)},2 * 60 * 1000)}Copy the code


4. WebSocket application

  1. Two-way communication, as in a chat room.

  2. Wechat applet encapsulates WebSocket. Wx.connectsocket () creates a WebSocket instance, SocketTask.

  3. Socket. IO supports WebSocket, polling, and HTTP streams.