SocketIO, Websocket disconnect and reconnect problem troubleshooting solution

I have used SocketIO and Websocket for a long time, and various websocket disconnection and reconnection problems have appeared in different projects due to the complexity of the network and the different agents. This article summarizes the disconnection and reconnection problems in the use of websocket, mainly the problems in the use of SocketIO. The first is the problem encountered in the Nginx proxy, because websocket is upgraded from HTTP protocol to websocket, so we cannot configure the proxy of websocket exactly like configuring HTTP proxy. The following is the official websocket configuration provided by Nginx:

location /chat/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

The above configuration must configure proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; these two options, otherwise there will be disconnection and reconnection problems. The second HTTP protocol must be 1.1, not 1.0, otherwise the problem of disconnection and reconnection will occur.

After confirming that there is no problem with the proxy configuration, if there is still a disconnection and reconnection problem, we need to capture the packet to troubleshoot the problem, because the complexity of the network, firewall, network configuration and other issues may cause problems with the sent packets , Resulting in failure to reconnect. Here we take the socket.io connection as an example. Socket.io does not directly upgrade http to websocket at the beginning, but first sends an http request to obtain some parameters required by the client such as sid. The packet capture is as follows:

 The above is the content of the HTTP request, and the unique identifier of the sid server will be returned. The upgrade protocol is websocket, the ping interval is 5000 milliseconds, that is, the heartbeat interval is 5 seconds, and the timeout is 25000 milliseconds, that is, if you do not send a heartbeat for 25 seconds, the connection will be disconnected. . The request for upgrading the HTTP protocol to the websocket protocol is as follows:

The main content of the sent packet is drawn by the grid in the above figure, and the content inside is indispensable. Sometimes the content of the circled packet is lost due to firewall or other reasons, which leads to continuous disconnection and reconnection. This article is mainly about troubleshooting some ideas of websocket disconnection and reconnection. When websocket disconnection and reconnection, you can check from these perspectives. There is also Nginx proxy if there are multiple websocket services, you must use the iphash strategy to forward requests, otherwise it will Cause disconnection and reconnection problems.

Guess you like

Origin blog.csdn.net/wk19920726/article/details/109023816