First, WebSocket introduction

WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5. WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.

WebSocket, a network transport protocol, is located at the application layer of OSI model. Full-duplex communication can be implemented over a single TCP connection, saving server resources and bandwidth and achieving real-time communication

Websocket is a network communication protocol, we all know HTTP protocol, HTTP protocol can only be initiated from the client, can not push data from the server to the client. WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. It must rely on THE HTTP protocol to complete a handshake between the browser and the server. After the handshake is successful, a persistent connection can be created between the two and two-way data transfer can be carried out (data is transferred directly through the TCP channel, regardless of HTTP). That is, Websocket is divided into handshake and data transmission stages, that is, HTTP handshake + duplex TCP connection.

In order to implement push technology, many websites use Ajax polling. (timer +Ajax), the browser sends HTTP requests to the server, and then 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.

The WebSocket protocol defined by HTML5 can better save server resources and bandwidth, and can communicate in more real time.

Its biggest characteristic is that the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, is a real two-way equal dialogue, belongs to a server push technology.

Other features include:

  • Based on TCP protocol, the implementation of the server side is relatively easy.
  • Good compatibility with HTTP, default ports 80 and 443. In addition, the handshake phase adopts HTTP protocol, so it is not easy to shield the handshake and can pass various HTTP proxy servers.
  • The data format is relatively light, with low performance overhead and high communication efficiency.
  • You can send text or binary data.
  • There are no same-origin restrictions, and clients can communicate with any server.
  • Full duplex (communication allows data to be transmitted simultaneously in two directions, which is equivalent in capability to the combination of two simplex communication modes, e.g. A→B at the same time B→A, instantaneous synchronization)
  • The protocol identifier is WS (or WSS if encrypted), and the server URL is the URL.
ws://www.chrono.com
ws://www.chrono.com:8080/srv
wss://www.chrono.com:445/im?user_id=xxx
Copy the code

Second, the WebSocket API

The browser sends it to the server

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Copy the code
  • Upgrade: websocket 和 Connection: Upgrade, tell nginx, Apache, etc that the request iswebsocketThe request.
  • Sec-WebSocket-KeyIs a Base64 encode value, which the browser randomly generates to tell the server: Peat, don’t cheat, I want to verify that Ni is really a Websocket assistant.
  • Sec_WebSocket-ProtocolIs a user-defined string used to distinguish protocols required by different services at the same URL. I’m going to serve A tonight. Make no mistake
  • Sec-WebSocket-VersionIs to tell the server what to useWebsocket Draft(Protocol version)

The server returns:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
Copy the code
  • Similarly, Upgrade: websocket and Connection: Upgrade tell the browser to successfully switch the protocol to WebSocket.

  • Sec-websocket-accept is the sec-websocket-accept Key that is authenticated by the server and encrypted. Server: ok ok, know, show you my ID CARD to prove the line.

  • Sec-websocket-protocol is the final Protocol to use.

  • WebSocket constructor

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

    var Socket = new WebSocket('wss://echo.websocket.org');
    Copy the code

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

  • webSocket.readyState

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

    Here is an example.

    Switch (socket. readyState) {case websocket. CONNECTING: console.log(' CONNECTING! ') break; Case websocket. OPEN: console.log(' Connection successful! ') break; Case websocket. CLOSING: console.log(' Connection is CLOSING! ') break; Case websocket. CLOSED: console.log(' Connection CLOSED! ') break; default: // this never happens break; }Copy the code
  • WebSocket event

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

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

    Socket.onopen = function () { console.log('Hello Word! '); };Copy the code

    If you want to specify multiple callback functions, you can use the addEventListener method.

    Socket.addEventListener('open', function (event) { console.log('Hello Word! '); });Copy the code
  • WebSocket method

    methods describe
    Socket.send() Use the connection to send data
    Socket.close() Close the connection

    Example of sending text.

    Socket.send('your message');
    Copy the code

    Example of sending a Blob object.

    var file = document.querySelector('input[type="file"]').files[0];
      Socket.send(file);
    Copy the code

Three, the traditional way

Traditional Polling

In current Web applications, it is a common continuous communication mode, which is usually implemented by setInterval or setTimeout. For example, if we wanted to periodically fetch and refresh data on a page, we could write the following implementation in combination with Ajax:

setInterval(function() {
    $.get("/path/to/server", function(data, status) {
        console.log(data);
    });
}, 10000);
Copy the code

The program requests data from the server every 10 seconds and stores it when it arrives. This method usually can meet the requirements of simple, yet at the same time there are a lot of defects: under the condition of the network is not stable, the server receives the request, sends a request to the client receives the request total time could be more than 10 seconds, and the request is sent 10 seconds interval, this will lead to the received data to arrive at the order in which they do not agree with the order. So there is polling using setTimeout:

function poll() { setTimeout(function() { $.get("/path/to/server", function(data, status) { console.log(data); Poll (); }); }, 10000); }Copy the code

The program is set to initiate a request 10 seconds after the data is returned, then initiate a second request 10 seconds after the data is returned, and so on. This does not guarantee a fixed time interval between requests, but it does guarantee the order in which the data arrives.

defects

The program creates a new HTTP request for each request, but does not always return the required new data. When the number of simultaneous requests reaches a certain level, the load on the server becomes heavy.

Long Poll

After the client sends a request, the server takes the connection and returns a response to the client if there is a message. No message, no response is returned. The client then sends the request again, repeating the previous action.

conclusion

The HTTP protocol is characterized by the fact that the server cannot initiate contact with the client. Its passivity indicates that the two-way communication needs to be continuously connected or always open, which requires fast processing speed or high concurrency capacity of the server and is very resource-consuming.

Four advantages,

  • Less control overhead: The packet header protocol is smaller, unlike HTTP, which requires each request to carry a complete header
  • Better real-time: Compared to HTTP requests that require the client to initiate the request before the server can respond, the latency is significantly less
  • Keep-create state: After a communication is created, the status information can be omitted, unlike HTTP, which requires authentication for each request
  • Better binary support: Binary frames are defined for better handling of binary content
  • Support extension: Users can extend the WebSocket protocol and implement some customized sub-protocols
  • Better compression: Websocket, with appropriate extension support, can use the context of previous content, which can significantly improve compression when passing similar data

Five, WebSocket application

  • Instant chat – Chat with multiple people
  • The weather
  • Background statistics updated
  • Message push (panic buying, SEC kill alert)
  • Mall backstage commodity editor is locked
  • Coordinate document editing

Six, summarized

  1. websocketIs a similarhttpA communication protocol.
  2. websocketThe biggest feature is that clients and servers can send messages to each other.
  3. websocketWidely used in applications that require real-time communication.
  4. websocketThere is no homologous restriction, and the performance cost is low, and the communication is efficient.

Reference article:

Juejin. Cn/post / 686349…

Github.com/febobo/web-…