What is websocket

WebSocket is a communication protocol that enables full-duplex communication over a single TCP connection. WebSocket makes it easier to exchange data between the client and the server, 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 establish a persistent connection and two-way data transfer

First of all, it is important to understand that WebSocket is a communication protocol, which is different from HTTP protocol. HTTP protocol can only realize the single communication of client request and server response. WebSocket can achieve two-way communication between the client and the server. To put it bluntly, the biggest and most obvious difference is that the server can actively push the message to the client.

Two, several methods of real-time communication with the server

As we all know, there are generally two ways to interact with a server in real time without using websockets.

  1. AJAX polling
  2. Long Polling Long Polling.

AJAX polling

AJAX polling is a timed request, which is a normal client-server communication process, but in an infinite loop, so that the server can be retrieved as soon as the latest information is available to the client.

Long Polling Long Polling

Long Polling means that the client maintains a Long connection with the browser and disconnects when the server returns a message. And then reconnect. It’s a circular process.

The client initiates a Long Polling. If the server has no data to return, it holds the request and returns it to the client when it has data. The client then launches another Long Polling and repeats the process again.

Disadvantages Both of these methods have fatal weaknesses, such as high cost and passivity. This is a test for the server, assuming high concurrency. WebSocket features such as handshake, persistent connection, and active push can solve these problems without sacrificing performance.

HTTP HTTPS WS WSS four differences

Third, the client API

3.1 WebSocket constructor

The WebSocket object is used as a constructor to create a new WebSocket instance.

var ws = new WebSocket('ws://localhost:8080');
Copy the code

After executing the above statement, the client will connect to the server.

Protocol,

First, the client initiates a protocol upgrade request. As you can see, the standard HTTP packet format is adopted and only the GET method is supported. GET / HTTP/1.1
Host: localhost:8080
Origin: http:/ / 127.0.0.1:3000
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: w4v7O6xFTi36lq3RNcgctw==
// Key request header meaning as follows:Connection: Upgrade: indicates the protocol to be upgraded. Upgrade: indicates the websocket protocol to be upgraded. Sec-WebSocket-Version:13: Indicates the websocket version. If the server does not support the version, you need to return an sec-websocket-versionheader containing the version number supported by the server. Sec-websocket-key: is compatible with the sec-websocket-accept at the beginning of the server response, providing basic protection, such as malicious or unintentional connections.Copy the code

3.2 the webSocket. ReadyState

The readyState property returns the current state of the instance object, of which there are four types. CONNECTING: value is0Is connected. OPEN: the value of1"Indicates that the connection is successful and communication can be started. CLOSING: value is2, indicating that the connection is being closed. CLOSED: the value of3", indicating that the connection is closed or the connection fails to be openedCopy the code

3.3 the webSocket. Onopen

The onopen property of the instance object, which specifies the callback function if the connection is successful.

ws.onopen = function () {
  ws.send('Hello Server! ');
}
// If you want to specify multiple callback functions, use the addEventListener method.
ws.addEventListener('open'.function (event) {
  ws.send('Hello Server! ');
});

Copy the code

3.4 the webSocket. Onclose

The onClose property of the instance object, which specifies the callback function if the connection is closed.

ws.onclose = function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
};

ws.addEventListener("close".function(event) {
  var code = event.code;
  var reason = event.reason;
  var wasClean = event.wasClean;
  // handle close event
});

Copy the code

3.5 the webSocket. Onmessage

The onMessage property of the instance object, which specifies the callback function to receive data from the server.

ws.onmessage = function(event) {
  var data = event.data;
  // Process data
};

ws.addEventListener("message".function(event) {
  var data = event.data;
  // Process data
});
// Note that the server data can be either text or binary (blob objects or Arraybuffer objects)
Copy the code
ws.onmessage = function(event){
  if(typeof event.data === String) {
    console.log("Received data string");
  }

  if(event.data instanceof ArrayBuffer) {var buffer = event.data;
    console.log("Received arraybuffer"); }}Copy the code

3.6 the webSocket. The send ()

The send() method of the instance object is used to send data to the server.

  • Example of sending text.
ws.send('your message');
Copy the code
  • Example of sending a Blob object.
var file = document
  .querySelector('input[type="file"]')
  .files[0];
ws.send(file);
Copy the code
  • An example of sending an ArrayBuffer object.
// Sending canvas ImageData as ArrayBuffer
var img = canvas_context.getImageData(0.0.400.320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
  binary[i] = img.data[i];
}
ws.send(binary.buffer);
Copy the code

3.7 the webSocket. BufferedAmount

The bufferedAmount property of the instance object, indicating how many bytes of binary data remain unsent. It can be used to determine whether the transmission is complete.

var data = new ArrayBuffer(10000000);
socket.send(data);

if (socket.bufferedAmount === 0) {
  // Send complete
} else {
  // Send is not finished yet
}

Copy the code

3.8 the webSocket. Onerror

The onError property of the instance object, which specifies the callback function when an error is reported

var data = new ArrayBuffer(10000000);
socket.send(data);

if (socket.bufferedAmount === 0) {
  // Send complete
} else {
  // Send is not finished yet
}

Copy the code

Four,

  • The server can actively push messages to the client.
  • Lightweight data format with low performance overhead. When the client exchanges data with the server, the data header from the server to the client is 2 to 10 bytes, and the mask from the client to the server needs to be added with another 4 bytes. HTTP needs to carry the full header each time.
  • Better binary support, can send text, and binary data
  • There are no same-origin restrictions, and clients can communicate with any server
  • The protocol identifier is WS (or WSS if encrypted), and the requested address is the backend WebSocket-enabled API.
  • Because the HTTP protocol has a flaw: communication can only be initiated by the client
  • It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers.
  • The protocol identifier is WS (or WSS if encrypted), and the server URL is the URL. Such as: ws://example.com: 80 / some/path
  • The most typical scenario is a chat room

Five, the reference

  • Nguyen one: www.ruanyifeng.com/blog/2017/0…

The last

Recently, I was working on a chat room project, in which I first sent HTTP requests to obtain information such as users’ tokens and then set up websockets.

There are a lot of things WebSocket can write, such as WebSocket extensions. How clients and servers negotiate and use extensions. WebSocket extensions can add a lot of power and imagination to the protocol itself, such as data compression, encryption, and multiplexing, as well as the initial proposal for data encryption processing. Based on the consideration of safety and efficiency, a compromise scheme is finally adopted: mask processing for data load.

Space is limited, here not to expand, interested students can leave a message exchange. Please point out any mistakes or omissions in the article