What you have to know about websocket

1. What is websocket? (real time + encryption)

WebSocket is a full-duplex communication protocol based on the TCP protocol, which can establish a persistent connection between the client and the server to achieve two-way communication. The advantage of the WebSocket protocol is that it can provide real-time data transmission and achieve low-latency communication effects.

WebSocket has the following differences from the traditional HTTP protocol:

  1. Connection method: HTTP protocol is a request-response protocol. The client sends a request, and the server closes the connection immediately after returning the response; while the WebSocket protocol is a long-term connection protocol. A persistent connection is established between the client and the server, and the connection can be maintained State, realize real-time data transmission and communication.
  2. Data format: The data format transmitted by the HTTP protocol is mainly text and binary data, while the data format transmitted by the WebSocket protocol can contain any type of data, such as text and binary data.
  3. Transmission efficiency: Since the WebSocket protocol is a long-term connection protocol, it can avoid the overhead of frequently establishing and closing connections, so it has better performance in terms of transmission efficiency.
  4. Security: The data transmission of the HTTP protocol is transmitted in plain text, which is easy to be eavesdropped and tampered with; while the WebSocket protocol can be encrypted through the TLS/SSL protocol to improve the security of data transmission.
  5. Application scenarios: The HTTP protocol is suitable for scenarios where the client requests the server to obtain a response, such as browser loading web pages, downloading files, etc.; the WebSocket protocol is suitable for scenarios such as real-time communication and real-time data transmission, such as online games, instant messaging, etc.

Therefore, compared with the traditional HTTP protocol, the WebSocket protocol has better performance in terms of real-time performance, transmission efficiency and security, and is suitable for some specific application scenarios.

The use of the WebSocket protocol requires both the client and the server to support the protocol. The client usually uses the WebSocket API in JavaScript to establish a connection with the server and send data, while the server needs to implement the relevant code of the WebSocket protocol to process the client request and send data. Commonly used server-side implementations include the ws module of Node.js and the Java-WebSocket library of Java.

2. The case of webSocket used in the Internet of Things platform

The WebSocket protocol is widely used in IoT platforms, the following are some possible cases:

  1. Smart home control: Smart home is one of the typical scenarios of IoT applications. By using the WebSocket protocol, real-time communication and data transmission between smart home devices can be realized, such as smart lighting control, smart door lock control, etc.
  2. Industrial automation control: Industrial automation control is another typical scenario of IoT applications. In industrial automation, the WebSocket protocol can be used to monitor and control the status of equipment in real time, such as industrial robot control, intelligent warehouse management, etc.
  3. Logistics monitoring: Logistics monitoring is another important field of IoT applications. By using the WebSocket protocol, the location, temperature, humidity and other data during logistics transportation can be monitored in real time, thereby improving the efficiency and safety of logistics management.
  4. Smart agriculture: Smart agriculture is an emerging field of IoT applications. By using the WebSocket protocol, the status of agricultural equipment can be monitored and controlled in real time, such as greenhouse climate control, automatic irrigation systems, etc.

These cases are only part of the application of the Internet of Things. In fact, the application scenarios of the WebSocket protocol in the Internet of Things platform are very rich, and appropriate technical solutions can be selected according to specific application scenarios and requirements.

3. Practical use cases

Scenes:

The front end sends a request to the back end, indicating that it wants to control some devices.

The backend sends an instruction to the device to turn on the device, but since the time from the device to the backend is too long, if the device returns to the backend at this time and then returns to the frontend, the waiting time for the frontend will be very long. Long.

solution:

1. Asynchronous call:

Asynchronous calls can be used to process responses from the device. After the backend sends the command to the device, it can immediately return a response to the frontend, and at the same time start an asynchronous task to wait for the response from the device. When the device responds, the asynchronous task will immediately process the response and return the result to the front end.

Disadvantages : Using asynchronous calls, because you return a response to the front end, the front end thinks that the device has been controlled, and will get the current status of the device. It may happen that the front end has refreshed the page before the status of the device has been updated, resulting in data errors .

Optimization scheme : In order to avoid this situation, a long connection can be established between the front end and the back end, so as to realize real-time communication and data transmission.

By using the WebSocket protocol, real-time communication and data transmission between the client and the server can be realized, thereby avoiding the problem of data errors. In addition, WebSocket can also improve the real-time and response speed of the application, thereby enhancing the user experience.

  1. The front-end establishes a WebSocket connection: the front-end code uses the WebSocket API in JavaScript to establish a WebSocket connection with the back-end, so that real-time communication between the client and the server can be realized.
  2. The backend sends the command to the device: the backend sends the command to the device, and starts an asynchronous task to wait for the response from the device.
  3. The device side sends the status update to the backend: the device side sends the status update to the backend, the backend forwards the status update to the frontend, and the frontend receives the status update through WebSocket and updates the data in the page.

2. Polling:

You can use the polling method on the front end to obtain the response from the device. After the front-end sends commands, it can periodically send requests to the back-end to obtain responses from the device until a response is received. Although the polling method cannot realize real-time communication, it can guarantee to obtain the response from the device within a certain period of time, thereby avoiding the problem of long waiting time.

How to use webSocket in the front end

SocketJS is a WebSocket-based JavaScript library that provides an easy way to achieve real-time data transfer and two-way communication. Here are the simple steps to use SocketJS on the front end:

  1. Introduce SocketJS library: Introduce SocketJS library in HTML page, for example:
<script src="<https://cdn.jsdelivr.net/npm/[email protected]/dist/sockjs.min.js>"></script>

  1. Create a WebSocket connection: use SockJSthe objects provided by the SockJS library to create a WebSocket connection, for example:
const socket = new SockJS('/websocket');

Here a WebSocket connection is created and the URL of the connection is specified as /websocket.

  1. Listening to WebSocket events: socketListening to WebSocket events through objects, for example:
socket.onopen = function() {
    
    
  console.log('WebSocket连接已建立');
};

socket.onmessage = function(event) {
    
    
  console.log('收到服务器发送的消息:', event.data);
};

socket.onclose = function() {
    
    
  console.log('WebSocket连接已关闭');
};

onopenHere, the WebSocket , onmessageand events are monitored onclose, and the corresponding callback function is executed when the event occurs.

  1. Send data: Use socket.send()the method to send data to the server, for example:
socket.send('Hello, server!');

Here a string message is sent to the server.

In short, using SocketJS can simply realize the front-end WebSocket connection and data transmission, so as to realize the functions of real-time data transmission and two-way communication. It should be noted that when using SocketJS, the server side also needs to implement the corresponding WebSocket protocol code to process client requests and send data.

complete case

The front end sends a request to the back end, indicating that it wants to control some devices.

The server sends instructions to the device.

When the device returns to the server that it has been turned on.

The backend passes this data back to the frontend.

When the WebSocket protocol is used, real-time two-way communication can be realized. The following is a more advanced case based on the WebSocket protocol, which is used to control the switch of the device:

Server side code:

const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();

// 创建 HTTP 服务器
const server = http.createServer(app);

// 创建 WebSocket 服务
const wss = new WebSocket.Server({
    
     server });

// 模拟设备状态
let deviceStatus = 'off';

// 监听 WebSocket 连接
wss.on('connection', function connection(ws) {
    
    
  console.log('WebSocket connected');

  // 监听 WebSocket 消息
  ws.on('message', function incoming(message) {
    
    
    console.log('received: %s', message);

    // 解析消息内容
    const data = JSON.parse(message);

    // 如果消息类型为控制设备开关
    if (data.type === 'control') {
    
    
      // 模拟控制设备开关
      if (data.value === 'on') {
    
    
        deviceStatus = 'on';
      } else if (data.value === 'off') {
    
    
        deviceStatus = 'off';
      }

      // 发送设备状态给前端
      ws.send(JSON.stringify({
    
     type: 'status', value: deviceStatus }));
    }
  });
});

// 启动服务器
server.listen(3000, function() {
    
    
  console.log('Server is running on port 3000');
});

Front-end code:

const socket = new WebSocket('ws://localhost:3000');

const buttonOn = document.getElementById('button-on');
const buttonOff = document.getElementById('button-off');
const statusLabel = document.getElementById('status-label');

socket.addEventListener('open', function(event) {
    
    
  console.log('WebSocket connected');
});

socket.addEventListener('message', function(event) {
    
    
  console.log(`Message from server: ${
      
      event.data}`);

  // 解析消息内容
  const data = JSON.parse(event.data);

  // 如果消息类型为设备状态
  if (data.type === 'status') {
    
    
    statusLabel.innerHTML = `Device status: ${
      
      data.value}`;
  }
});

buttonOn.addEventListener('click', function() {
    
    
  // 发送控制消息给服务器
  const message = JSON.stringify({
    
     type: 'control', value: 'on' });
  socket.send(message);
});

buttonOff.addEventListener('click', function() {
    
    
  // 发送控制消息给服务器
  const message = JSON.stringify({
    
     type: 'control', value: 'off' });
  socket.send(message);
});

The above code shows a basic WebSocket communication process for controlling the switch of the device. The front end connects to the server through the WebSocket object, sends a control message to the server, and the server simulates the switch of the control device and returns the device status to the front end. In practical applications, the function and performance of WebSocket communication can be further expanded and optimized according to specific needs and scenarios.

Guess you like

Origin blog.csdn.net/qq_43720551/article/details/131692373