jeremygo

jeremygo

我是把下一颗珍珠串在绳子上的人

WebSocket Practice

When working on a mini-program project, there is a need for real-time communication. Here, we will organize the knowledge of WebSocket.

About WebSocket#

  • Introduction: The information exchange process of a web application is generally that the client sends a request through the browser, the server receives the request, processes it, and returns the result to the client. Then the client's browser parses the information. This mechanism is quite limited for applications with high real-time requirements. Therefore, there is a need for an efficient and energy-saving bidirectional communication mechanism to ensure real-time data transmission. WebSocket was born to meet this need.
  • Concept:
    • MDN: WebSocket is an advanced technology that allows for bidirectional conversations between clients and servers. With this API, you can send messages to the server and receive event-driven responses, eliminating the need to poll the server for data.
    • WebSocket is also known as web TCP, which is used for communication. As a new communication protocol introduced in HTML5, it consists of TCP protocol and programming API. It can establish a bidirectional connection between the browser and the server, giving the browser native real-time communication capabilities in an event-driven manner, thereby extending our web applications and improving application performance and user experience.
  • Why use it:
    Before WebSocket appeared, there were some other real-time communication solutions, such as polling, long polling, and server-sent events.
    • Polling: The client sends requests to the server at regular intervals to keep the client and server data synchronized through frequent requests. It is usually implemented using setInterval or setTimeout. Problem: When the client sends requests to the server at a fixed frequency, the server's data may not have been updated, resulting in many unnecessary requests, wasting bandwidth and being inefficient.
    • Long Polling: An improvement and enhancement of timed polling. When the server has no data updates, the connection will be kept for a period of time until the data or status changes or the time expires, reducing unnecessary interaction between the client and the server. Problem: If the server's data changes frequently, there is no fundamental performance improvement compared to timed polling.
    • Server-Sent Events: It is a part of the HTML5 specification and can achieve one-way data communication from the server to the client. Through SSE, the client can automatically receive data updates without repeatedly sending HTTP requests. Problem: It only supports one-way event pushing from the server to the client, and all versions of IE do not support SSE.
    • WebSocket: Compared to traditional Ajax polling solutions, WebSocket has great performance advantages in terms of traffic and load, and it is not complicated to develop. You only need to instantiate WebSocket to create a connection, and then you can send corresponding messages after the connection is successful.

Node Implementation#

Here, we use the ws library of Node to implement a simple WebSocket server.

  • Server:
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({
    port: 3001
});

wss.on("connection", function(ws) {
    ws.on("message", function(msg) {
        console.log(msg);
        ws.send("Nice to meet you!");
    });
    ws.on("close", function() {
        console.log("Stop client");
    });
});
  • Mini-program client:
wx.connectSocket({
    url: 'Server Link:3001',
    data: {},
    header: {
        'content-type': 'application/json'
    },
    method: 'GET',
    success: function() {
        console.log("Client connected");
    }
}),
wx.onSocketOpen(function() {
    console.log("WebSocket connection opened");
    wx.sendSocketMessage({
        data: 'Hello!'
    });
}),
wx.onSocketMessage(function(msg) {
    console.log("Received: "+ msg);
});

I would like to mention wx.onSocketMessage() because it only accepts string and binary data types. Therefore, if you need to send JSON-formatted data, you need to convert it. As long as WebSocket is supported, it definitely supports the native window.JSON, so you can directly use JSON.parse() and JSON.stringify() for conversion.

This completes a basic example of bidirectional communication.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.