background

In the past, Ajax polling or long polling was used to handle applications with high real-time requirements. Disadvantages: 1, HTTP request is stateless, each request will have header; 2. The server needs to maintain two TCP connections for each client (one for sending information to the client and one for receiving data).

HTML5 has a new protocol websocket, which supports the use of full-duplex communication between the client and the server. It can be used for applications with high real-time requirements, such as games, stock trading, multi-user collaboration and so on.

Protocol overview

The protocol is divided into two parts: handshake and data transfer

Shake hands

Websocket is based on TCP and uses HTTP to achieve the Upgrade request, using port 80/443

1, The client sends a request:

GET/XXX HTTP/1.1 Request URL: WSS :// XXX.xxx.xxx /ws Connection: Upgrade Host: XXX.xxx.xxx Origin: https://xxx.xxx Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Sec-WebSocket-Key: Wul5+39fW+VU4hdALTiCWw== Sec-WebSocket-Version: 13 Sec-WebSocket-Protocol: chat, superchat Upgrade: websocketCopy the code

2. The server then returns the following message indicating that it has received the request, successfully established the Websocket, and tells the client that the Websocket protocol is about to be upgraded

HTTP/1.1 101 Switching Protocols Connection: Upgrade Date: Thu, 09 Aug 2018 06:19:08 GMT SEC-websocket-Accept: ERPVeRRPyTlkPDZoozDLvc0mBsM = the Sec - the WebSocket Protocol: chat Server: nginx / 1.13.12 Upgrade: WebSocketCopy the code
  • Sec-websocket-key is a Base64 encode value, which is randomly generated by the browser

  • Sec_websocket-protocol is a user-defined string used to distinguish protocols required by different services under the URL

  • Sec-websocket-version tells the server the WebSocket Draft (protocol Version) to use

  • Sec-websocket-accept is the sec-websocket-accept Key that is authenticated by the server and encrypted

  • Sec-websocket-protocol indicates the final Protocol used

Sec-websocket-accept Base64-encoded (SHA-1(sec-websocket-key + 258eAFa5-E914-47DA-95ca-C5AB0DC85b11))

To transmit data

Support formats: Textual Data, Binary data, Control Frames, etc

WebSocket URIs

ws-URI = "ws:" "/ /" host [ ":" port ] path [ "?" query ]
wss-URI = "wss:" "/ /" host [ ":" port ] path [ "?" query ]
Copy the code

Data frame

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127)   |
     | |1|2|3|       |K|             |                               |
     +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
     |     Extended payload length continued, if payload len == 127  |
     + - - - - - - - - - - - - - - - +-------------------------------+
     |                               |Masking-key, if MASK set to 1  |
     +-------------------------------+-------------------------------+
     | Masking-key (continued)       |          Payload Data         |
     +-------------------------------- - - - - - - - - - - - - - - - +
     :                     Payload Data continued ...                :
     + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
     |                     Payload Data continued ...                |
     +---------------------------------------------------------------+
Copy the code

Client example

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

socket.binaryType = "arraybuffer";

// Connection opened
socket.addEventListener('open'.function (event) {
    socket.send('Hello Server! ');
});

// Listen for messages
socket.addEventListener('message'.function (event) {
    console.log('Message from server ', event.data);
});
Copy the code

Constants & Attributes

WebSocket.readyState

Determine the current state of the WebSocket connection against the following constants:

Websocket. CONNECTING: The value is 0, indicating that a connection is being established. Websocket. OPEN: the value is 1, indicating that the connection is successful and communication can be started. Websocket. CLOSING: A value of 2 indicates that the connection is CLOSING. Websocket. CLOSED: if the value is 3, the connection is CLOSED or the connection fails to be opened.Copy the code

WebSocket.binaryType

Use binary data type connections

WebSocket.bufferedAmount

Returns the number of bytes of data that has been queued by the send() method but has not yet been sent to the network.

WebSocket.onclose

Used to specify the callback function after the connection is closed

WebSocket.onerror

Used to specify the callback function if the connection fails

WebSocket.onmessage

Used to specify the callback function when information is received from the server

WebSocket.onopen

Used to specify the callback function after a successful connection

methods

WebSocket.close([code[, reason]])

Close current link

WebSocket.send(data)

Sends data to the server

Browser compatibility

Obviously, to support WebSocket communication, browsers need to support this protocol. Currently supported browsers:

Chrome

Firefox

IE >= 10

Sarafi >= 6

Android > = 4.4

iOS >= 8

reference

Tools.ietf.org/html/rfc645…

Developer.mozilla.org/zh-CN/docs/…

Welcome to “Web notebook”, receive front-end learning materials, join the high quality communication group to learn ~