Home > Web Front-end > JS Tutorial > JavaScript and WebSocket: Create an efficient real-time data collection system

JavaScript and WebSocket: Create an efficient real-time data collection system

PHPz
Release: 2023-12-18 13:00:51
Original
681 people have browsed it

JavaScript and WebSocket: Create an efficient real-time data collection system

JavaScript and WebSocket: Create an efficient real-time data collection system

In modern web applications, the processing of real-time data is becoming more and more common. Since transmitting arbitrary real-time data requires avoiding delays, we need to use an efficient communication method. This article will introduce how to use JavaScript and WebSocket to build an efficient real-time data collection system, and provide specific code examples.

WebSocket is a full-duplex protocol that allows long-term connections between clients and servers. When the amount of data required is large, WebSocket often has advantages over using HTTP communication transport. In addition, the WebSocket protocol is used simultaneously with the HTTP protocol, which makes it easier to integrate into existing web applications.

The following is a basic implementation example:

  • First, create a WebSocket object:

    var socket = new WebSocket('ws:// example.com/socket');

This will create an online WebSocket object, which establishes a long-term connection with the server. The URL 'ws://example.com/socket' points to the WebSocket server.

  • Next, listen to WebSocket events:

    socket.addEventListener('open', function (event) {

      console.log('WebSocket连接已建立');
    Copy after login

    });

    socket.addEventListener('message', function (event) {

      console.log('Received:', event.data);
    Copy after login

    });

    socket.addEventListener('close', function (event) {

      console.log('WebSocket连接已关闭');
    Copy after login

    });

Here, the addEventListener() function is used to add an event handler to respond to WebSocket events. The 'open' event will be fired when the WebSocket connection is established, the 'message' event will be fired when data is received, and the 'close' event will be fired when the WebSocket connection is closed.

  • Finally, send/receive WebSocket data:

    socket.send('Hello World'); // Send data

    var data = JSON .parse(event.data); // Receive data

This simple example shows how to use JavaScript and WebSocket to establish a real-time connection from the client to the server. However, real applications require more code to handle more situations and technical details.

The following is a more complete WebSocket application example:

Server side

const WebSocket = require('ws');
const wss = new WebSocket.Server({
  port: 8080
});
console.log("WebSocket server started...");
 
wss.on('connection', function(ws) {
    console.log("WebSocket client connected...");
 
    ws.on('message', function(message) {
        console.log("Message received:"+message);
        if (message === 'close') {
            ws.close();
        }
        else {
            wss.clients.forEach(function each(client) {
                if (client.readyState === WebSocket.OPEN) {
                    console.log("Broadcasting:", message);
                    client.send(message);  // 实现广播
                }
            });
        }
    });
 
    ws.on('close', function() {
        console.log("WebSocket closed...");
    });
});
Copy after login
  • In this example, the server will accept the client connection when a message occurs will be broadcast to all connected clients. When a "close" message is received, the client's connection will be closed. Note that in order to implement broadcast, we need to loop through all clients connected to the server. Using WebSocket as the core of the real-time data collection system is an effective choice because it can ensure more efficient and stable transmission compared to HTTP transmission.

Client

var ws = new WebSocket('ws://localhost:8080');
console.log("WebSocket client started...");
 
ws.onmessage = function(msg) {
    console.log("Received: " + msg.data);
};
 
ws.onclose = function() {
    console.log("WebSocket closed...");
};
 
function send() {
    var val = document.getElementById('input').value;
    console.log("Sending: " + val);
    ws.send(val);
}
 
function close() {
    console.log("Closing WebSocket...");
    ws.send('close');
    ws.close();
}
Copy after login
  • The client code is as shown above, it will connect to the server WebSocket created earlier. When the client receives a message, it displays the message content. The "send" function will receive the text field value and send it to all clients on the WebSocket server. The "close" function will close the client WebSocket connection.

This article provides basic JavaScript and WebSocket implementation examples, as well as complete server and client example code. Anyone can get started using WebSockets and start building their own real-time data collection applications.

The above is the detailed content of JavaScript and WebSocket: Create an efficient real-time data collection system. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template