javascript websocket [heartbeat + service pushing information forward]

Posted by mator on Tue, 31 Mar 2020 03:17:16 +0200

1. [Role]
To maintain the sustainability and stability of the connection, the websocket heartbeat is the solution.
2. [Analysis]
1. If the device network is disconnected, the native websocket will not immediately trigger any events on the websocket, and the front end will not know if the current connection has been disconnected.
2. When we use the websocket.send method, the browser will find that the connection is broken.The onclose method is triggered.
3. Likewise, the back-end websocket service may cause disconnection, and the front-end will not receive notification of disconnection. Therefore, the front-end needs to send a heartbeat message [ping] periodically, and the back-end receives a ping-type message returning a pong message to inform the front-end that the connection is normal.Conversely, the connection is disconnected.
3. [Principles]
The front end is the most active, and the way to send ping messages regularly is through the browser's heartbeat mechanism.
4. [Difference between websocket and socket]
websocket is a new protocol for H5.It implements dual communication between browser and server.Establishing a handshake still requires the help of an http request.
The http protocol is a non-persistent, one-way network protocol.Only browsers are allowed to make requests after a connection is established can the server return the corresponding data.The browser keeps sending requests, and the requests are long headers: wasting traffic, server resources
Instant messaging is very common on websites, such as Web QQ.Previously, polling and Comet technology were commonly used.
WebSockets do this.Only the server and browser need to shake hands through the http protocol, and then set up a separate tcp communication channel for data transfer.
Handshake
The three handshakes of tcp connection between browser and server are the basis of communication.
After successful tcp connection, the browser transmits the version information supported by websocket to the server through http protocol.
After the server receives the client's handshake request, it also uses http laundry feedback data.
After the client receives the successful connection message, it uses the tcp channel for data transmission.
Three-time handshake
First handshake: The client sends data to the server, waiting for confirmation.
Second handshake: The server receives the data and resends the confirmation data to the client to confirm the connection request.
Third handshake: The client receives a confirmation from the server that the connection can be established by sending data to the server.
Q: Why three handshakes?
A: Three handshakes establish the connection to ensure that both sides of the communication have the ability to send and receive data.
Two times unsafe, four times unnecessary.

Four Waves
For the first wave, the client sends shutdown related data to the server and enters a waiting state;
After the second wave, the server receives the data related to the shutdown, sends the confirmation sequence number to the client, and the server enters the shutdown waiting state.
With the third wave, the server sends the data related to shutting down the server to the client again and enters the LAST_ACK state.
Fourth wave: When the client receives data from the shutdown server to the client, it enters the TIME_WAIT state, and then sends a confirmation number to the server.The server is eventually shut down.

Sockets are not really a protocol, but a level abstracted for the convenience of using TCP or udp.Is a set of interfaces between the application and transport layers.When two hosts communicate, they must connect through a socket, which uses the TCP/IP protocol to establish a TCP connection.TCP connections rely more on the underlying IP protocol, while IP connections rely on lower levels such as the link layer.
5. Examples

Client websocket Example:
//1. Request a Websocket object with a parameter that requires an address to connect to the server. As at the beginning of the HTTP protocol, the URL of the WebSocket protocol starts with ws://and the secure WebSocket protocol starts with wss://
var ws = new WebSocket("ws://echo.websocket.org"); 
//The WebSocket object supports four messages onopen, onmessage, onclose, and onerror
 ws.onopen = function(){ws.send("Test!"); }; 
 ws.onmessage = function(evt){console.log(evt.data);ws.close();}; 
 ws.onclose = function(evt){console.log("WebSocketClosed!");}; 
 ws.onerror = function(evt){console.log("WebSocketError!");};

When the connection between the browser and the server is successful, the onop Hmm message will be triggered.
If it fails, the onerror message is triggered.
The onmessage message is triggered when the browser receives the data sent by the server.
The onclose message is triggered when the browser receives a request from the server to close the connection.
All actions are triggered by sending a one-step callback.

6. Backend Code

//Turn on WebSocket support
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
                return new ServerEndpointExporter();
        }
}

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * Frozen
 * 2020 March 30, 2001 21:22:55
 */
@ServerEndpoint("/redant")
@Component
public class FrozenTest {
        /**
         * Normal Connection
         * @throws Exception
         */
     @OnOpen
        public void onOpen(Session session) throws Exception {
                sendMessage(session, "Which other boy was I before?");
                Thread.sleep(10000);//Send again in 10 seconds
                sendMessage(session, "Hi, HoYL´╝îThis is the server push data after 10 seconds!");
                 Thread.sleep(5000);//Send again in 10 seconds
    for (int i = 0; i < 100; i++) {
        Random random = new Random();
        sendMessage(session, String.valueOf(Math.random()*1000));
        Thread.sleep(5000);//Send again in 10 seconds
    }
        }
        /**
         * Implement Server Active Push
         */
        public void sendMessage(Session session, String message) throws Exception {
                session.getBasicRemote().sendText(message);
        }
}

7. Front End Test Code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Heart beat test</title>
        <script type="text/javascript" src="frozenjs/websocket.js" ></script>
        <script type="text/javascript" src="frozenjs/jquery-1.10.2.min.js" ></script>
    </head>
    <body>
        <div> 
            <span id="suppose" style="color: red; font-weight: bolder;"></span>
        </div>
    </body>
    <script>
        var url = "ws://127.0.0.1:8088/rest/2020/redant";
        var ws = new WebSocket(url);
        ws.onclose = function (e) {
        };
        ws.onerror = function (e) {
        };

        ws.onopen = function () {
            alert("Successful connection to server!");
        };
        ws.onmessage = function (event) {
            $("#suppose").text(event.data);
        }

    </script>
</html>

8. Image above
1. Successful handshake by server client

2. First Server Push Data

3. Second Server Push Data

4. Which long wait to follow

Topics: Web Development Session socket network Javascript