Realization of Websocket heartbeat packet reconnection

WebSocket

WebSocketSimilar to the standard TCP connection, it is a communication method defined by IETF (RFC 6455) for real-time full-duplex communication through TCP, which means it has more powerful functions and is often used in stock tickers and chat applications.

Compared to SSE, it can not only communicate bidirectionally, but can even handle binary content such as audio/video.

Principle :

The WebSocket protocol uses the 101 switchprotocol of the HTTP protocol (the server converts the protocol to the protocol listed in the Upgrade header according to the specification of the client) to achieve protocol conversion, switching from the HTTP protocol to the WebSocket communication protocol.

advantage:

Its biggest feature is that the server can actively push information to the client, and the client can also actively send information to the server. It is a real two-way equal dialogue and belongs to a kind of server push technology .

Other features include:

(1) Based on the TCP protocol, the server-side implementation is relatively easy.

(2) It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses the HTTP protocol, so it is not easy to shield during the handshake, and can pass through various HTTP proxy servers.

(3) The data format is relatively light, the performance overhead is small, and the communication is efficient.

(4) Text or binary data can be sent.

(5) There is no same-origin restriction, and the client can communicate with any server.

(6) The protocol identifier is ws(if encrypted wss), the server URL is the URL.

shortcoming:

websocket is a long-term connection, which is relatively limited by the network. It needs to handle reconnection. For example, when a user enters an elevator or a telecom user makes a phone call and the network is disconnected, reconnection is required. If ws cannot be reconnected all the time, some more complicated The business side will not be willing.

There are many pitfalls in websocket. If it’s just a single page, it’s okay, but if it involves multiple pages, timing push, and complicated push, it’s very easy to go wrong. Whether it’s the front end or the server end, you will encounter many, many problems

Generally, those with real-time data requirements will consider websocket

Specific connection method:

By adding upgrade: websocket and communication key (Sec-WebSocket-Key) in the request header, the two parties can successfully shake hands and establish full-duplex communication.
The specific connection method:

By adding upgrade: websocket and communication key (Sec-WebSocket-Key) in the request header, the handshake between the two parties is successful and full-duplex communication is established.

image-20210129154302429

(WebSocket client connection message)

image-20210129154325524

(WebSocket server response message)

  • Communication process:

Websocket is purely event-driven. Once a WebSocket connection is established, incoming data and changed connection status can be processed by listening to events. Data is transmitted in the form of frame sequence. After the server sends data, messages and events arrive asynchronously. WebSocket programming follows an asynchronous programming model, you only need to add a callback function to the WebSocket object to listen to events.

image-20210129154704375

websocket disconnected and reconnected (heartbeat packet)

The websocket is automatically disconnected when there is no message when it times out. Countermeasures:

At this time, we need to know the timeout period set by the server, and send the heartbeat packet within the timeout period. There are two schemes, one is that the client actively sends the uplink heartbeat packet, and the other is that the server actively sends the downlink heartbeat packet. The following mainly talks about how the client, that is, the front end, implements the heartbeat packet:.

First understand the heartbeat packet mechanism

The reason why the heartbeat packet is called a heartbeat packet is because it is sent at regular intervals like a heartbeat to tell the server that the client is still alive. In fact, this is to maintain a long connection. As for the content of this packet, there is no special regulation, but generally it is a small packet, or only contains an empty packet in the header.

In the TCP mechanism, there is a heartbeat packet mechanism, which is the TCP option: SO_KEEPALIVE. The system defaults to the set heartbeat frequency of 2 hours. However, it cannot detect disconnection such as power failure of the machine, unplugging of the network cable, or firewall. And the logic layer may not handle disconnection so well. Generally, if it is only used for keeping alive, it is still possible.

Heartbeat packets are generally implemented by sending empty echo packets at the logical layer. The next timer sends an empty packet to the client at a certain time interval, and then the client returns the same empty packet. If the server does not receive the feedback packet sent by the client within a certain period of time, it will only accept Said disconnected.

Under the long connection, there may be no data exchange for a long time. Theoretically, this connection is always connected, but in reality, it is difficult to know if the intermediate node fails. What's more terrible is that some nodes (firewalls) will automatically disconnect connections that have no data interaction within a certain period of time. At this time, we need our heartbeat packet to maintain long connections and keep alive.

Heartbeat detection steps:

  1. The client sends a probe packet to the server at intervals
  2. Start a timeout timer when the client sends a packet
  3. The server receives a detection packet and should respond with a packet
  4. If the client receives the response packet from the server, it means that the server is normal, delete the timeout timer
  5. If the client's timeout timer expires and the response packet is still not received, it means that the server is down

Front-end solution:

//心跳检测
var heartCheck = {
    
    
    timeout: 30000,        //30秒发一次心跳
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
    
    
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function(){
    
    
        var self = this;
        this.timeoutObj = setTimeout(function(){
    
    
            //这里发送一个心跳,后端收到后,返回一个心跳消息,
            //onmessage拿到返回的心跳就说明连接正常
            ws.send("ping");
            console.log("ping!")
            self.serverTimeoutObj = setTimeout(function(){
    
    //如果超过一定时间还没重置,说明后端主动断开了
                ws.close();     //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
}

Guess you like

Origin blog.csdn.net/qq_45473439/article/details/124401257