UniApp&WebSocket communication heartbeat mechanism & disconnection reconnection (front-end VUE3, back-end Express)

Table of contents

1. Websocket understanding (this is an explanation of websocket, if you have an understanding, you can directly see the following code implementation)

2. Build a WebSocket server in the Express backend framework

3. Explanation of the four states of the WebSocket server

4.Use Vue3 in Uniapp to build WebSocket client

5. UniApp&WebSocket communication heartbeat mechanism & disconnection reconnection (effect demonstration video)


1. Websocket understanding (this is an explanation of websocket, if you have an understanding, you can directly see the following code implementation)

  1. WebSocket is a new protocol under HTML5 (the websocket protocol is essentially a tcp-based protocol)
  2. It realizes the full-duplex communication between the browser and the server, which can better save server resources and bandwidth and achieve the purpose of real-time communication
  3. Websocket is a persistent protocol

2. WebSocket has the following characteristics:

  1. It is a true full-duplex mode. After the connection is established, the client and the server are completely equal and can actively request each other. The HTTP persistent connection is based on HTTP, which is a traditional mode in which the client initiates a request to the server.
  2. In the HTTP long connection, besides the real data part, the server and the client also need to exchange a large number of HTTP headers for each data exchange, and the efficiency of information exchange is very low. After the Websocket protocol establishes a TCP connection through the first request, the exchanged data can be exchanged without sending the HTTP header. This is obviously different from the original HTTP protocol, so it needs to upgrade both the server and the client. Implementation (mainstream browsers already support HTML5)
  3. The above is the reason why we use WebSocket when we write instant messaging.

2. Build a WebSocket server in the Express backend framework

  • First download the WebSocket package, command: npm i ws
  • After the package is downloaded, build the server (the following code is the built WebSocket server)

         Let me explain the above code: the above code websocket server (and heartbeat mechanism reply) has been set up

First define two empty arrays, the first array is used to store socket objects, and the second array is used to store the id of client login, which is used to distinguish who logged in and established a webscoket link, and then import it from the ws module WebSocketServer

Then create a server instance through new WebSocketServer, whoever connects to the websocket will create a websocket object, port is the defined port number, the client must be consistent, after server.on is linked, define a function in the parameter, and then pass this handleconnection The first parameter in the function is to monitor the client and monitor three states

3. Explanation of the four states of the WebSocket server

1. The status of successful connection 2. The status of close connection failure 3. The status of error connection error 4. Message status of receiving messages

  • 1. When the client closes the socket connection, the socket server will receive the message and execute this function to return some messages to the client.
  • 2. If there is an error in the client socket connection, the server will receive the message and execute this function to return some messages to the client.
  • 3. The socket will receive the message sent by the client, and the server will receive the message, and execute this function, and can do some messages back to the client.

Look at the 130 lines of code to pass an id from the browser, he is the user id of this login, and intercept him, and then add an id attribute to the ws, that is, the socket object, and judge the second defined by if Whether or not there is this id in the array, if not, I will push it in, if there is, do not operate, this judgment is used to prevent repeated logins from causing the wsidlist array to repeatedly add a person’s id, the first array wsList array is used to store The websocket object and id attribute are used to subsequently determine who the logged-in user wants to send a message to.

Then there is the last callback function handleMessage for receiving messages

Its parameters receive the data returned from the client, the data sent by the client is defined by itself, and then the received data needs to be parsed by tostring() and JSON.parse(), and the data is deconstructed after the parsing is completed.

You can see the judgment of the written switch, judge by the received mode parameter, what data is sent by the client, if it is message ordinary data, go to the first condition, and then perform the comparison by traversing the id in the socket object stored in wslist The id you want to send determines who you want to send to that user, and finally sends the data to the client through item.send() (the data also needs to be processed before sending), and the item is the socket object.

If it is the second HEART_BEAT heartbeat mechanism detection, then go to the second condition, which is to return data to the client, but the type is different. I have finished the code and explanation of building the WebSocket server above. The following is in Unipp uses Vue3 to build the client and establish a connection with WebSocket.

4.Use Vue3 in Uniapp to build WebSocket client

        1. After the page is mounted, call the api attribute provided in the uniapp official website. uni.connectSocket means to establish a connection with the server. My server port number is 8000, so the client must also be 8000, and localhost is your local machine Address, I am using it to demonstrate to everyone, so I use the address of this machine, or you can use the IP address of the other party you want to send to

The following code establishes a connection with the server.

        

        2. Send data to the server through the sendSocketMessage API provided by the uniapp official website, and write an add function callback to call this api to send data to the server. Note that my mode is MESSAGE type, so I send ordinary messages, and the data returned to the other party is what I send The data.

        

         3. This is to receive the data returned by the websocker server to the client. You can see that I also wrote a switch on the client to judge and distinguish what type of data the websocket returns to me, whether it is a normal message or a heartbeat mechanism. The chatlist is Used to render the page after receiving the data

        

         4. Finally, the following is, UniApp&WebSocket communication heartbeat mechanism & disconnection reconnection (core part)

        

         1: The heartbeat mechanism writes a timer, sends a message HEART_BEAT to the server regularly, and then the server returns HEART_BEAT.

You may have questions here, why write the heartbeat mechanism, because after the connection between WebSocket and the client is established, if there is no call for a long time, the WebSocket server will be disconnected, so the significance of writing the heartbeat mechanism is that the client goes to Detect if my WebSocket server is still alive, and if it is alive then reply me a message.

        2: Disconnection and reconnection, if there is no communication for a long time, the WebSocket server will be disconnected, so the user does not know after disconnection, and the data sent before is not passed to the other party, so disconnection reconnection is used. The properties in the uniapp official website are used

uni.onSocketError attribute API, this attribute means that if the server has an error, it will call this api. If my api is executed, I will call the disconnection reconnection function to establish a connection.

uni.onSocketClose attribute API, this attribute means that this api will be called if the server is closed,

If my api is executed, I will call the disconnection reconnection function to establish a connection.

5. UniApp&WebSocket communication heartbeat mechanism & disconnection reconnection (effect demonstration video)

PM me for the code

Guess you like

Origin blog.csdn.net/tianyhh/article/details/131000201