Node.js implements data push_node.js?1.1.2
Scenario: The backend update data is pushed to the client (the Java part uses Tomcat server).
There are many solutions for back-end push data, such as polling, Comet, and WebSocket.
1. Polling has the lowest development cost for the backend, which is to process Ajax requests and return data in the traditional way. When I was in school, the laboratory projects always used polling, because it is the safest and most reliable method. Easiest to implement. However, the waste of communication resources caused by polling cannot be ignored. No matter whether the data changes or not, the request is sent and responded as usual, and each HTTP request carries a long header information.
2. The concept of Comet is a long connection. After the client sends a request, the backend keeps the connection until the connection times out or the backend returns data and then re-establishes the connection, effectively transferring the communication resources to the server. What is actually consumed is server resources.
3. WebSocket is a full-duplex communication technology provided by HTML5. It realizes communication between the client and the server through "handshake". It has good real-time performance and carries a small header. It currently supports The browsers are as follows:
The ideal situation is to use the combination of WebSocket and Comet, and use the Comet method for browsers such as IE8 to perform downgrade processing. But in this way, the backend needs to implement two logics for processing requests, namely WebSocket and Comet. Therefore, this article adds Node.js. The reason for this is to transfer the logic of processing WebSocket (or Comet) to the Node.js part, so as not to "cause trouble" to the backend, because in actual situations, after the front-end developers push It's not easy being an end-user developer. Node.js serves as the middle layer for communication between the browser and the Java business logic layer, connecting the client and Tomcat, communicating with Tomcat through Socket (it is Socket, not WebSocket, and the backend needs to implement the Socket interface.
In the client On the client side, WebSocket and Comet are implemented through Socket.io. Socket.io will choose the appropriate implementation method (WebSocket, long pull...) for different browser versions or different clients. The introduction of Socket.io allows processing of WebSocket (or long pull..) Connection) becomes very easy. .js server code:
<script src="static/js/socket.io.js"></script>
Establishing a connection between the client and the Node.js server is only the first step. Next, you need to establish the Node.js server and Java business. Logical layer connection. At this time, the Node.js server acts as a client and sends a TCP connection request to Tomcat. After the connection is successful, the Node.js server and Tomcat establish a full-duplex channel, and it is the only one. How many client requests are forwarded from the Node.js server to Tomcat; similarly, the data pushed by Tomcat is also distributed to each client via the Node.js server.
var socket = io.connect('127.0.0.1:8181'); // 发送数据至服务器 socket.emit('fromWebClient', jsonData); // 从服务器接收数据 socket.on('pushToWebClient', function (data) { // do sth. });
var http = require('http'), app = http.createServer().listen('8181'), io = require('socket.io').listen(app); io.sockets.on('connection', function (socketIO) { // 从客户端接收数据 socketIO.on('fromWebClient', function (webClientData) { // do sth. }); // 客户端断开连接 socketIO.on('disconnect', function () { console.log('DISCONNECTED FROM CLIENT'); }); // 向客户端发送数据 socketIO.emit('pushToWebClient', jsonData); });
Node.js server code:
The above code omits some logic, such as what the Node.js server receives from Tomcat There are two types of data, one is the pushed data, and the other is the data in response to the request. The pushed data is processed uniformly here.
When processing communication, the data sent by Node.js to Tomcat is in String format, while the data received from Tomcat is in Buffer object (octal), which needs to be converted into String and then into json to send to the customer. end.
var http = require('http'), net = require('net'), app = http.createServer().listen('8181'), io = require('socket.io').listen(app), nodeServer = new net.Socket(); // 连接到Tomcat nodeServer.connect(8007, '127.0.0.1', function() { console.log('CONNECTED'); }); // 存储客户端的WebSocket连接实例 var aSocket = {}; // 同客户端建立连接 io.sockets.on('connection', function (socketIO) { // 从客户端接收数据,然后发送至Tomcat socketIO.on('fromWebClient', function (webClientData) { // 存储至映射表 aSocket[socketIO.id] = socketIO; // 发送至Tomcat的数据中添加socket_id webClientData['sid'] = socketIO.id; // 发送String类型的数据至Tomcat nodeServer.write(JSON.stringify(webClientData)); }); // 客户端断开连接 socketIO.on('disconnect', function () { console.log('DISCONNECTED FROM CLIENT'); }); }); // 从Tomcat接收数据 nodeServer.on('data', function (data) { var jsonData = JSON.parse(data.toString()); // 分发数据至客户端 for (var i in jsonData.list) { aSocket[jsonData.list[i]['sid']].emit('pushToWebClient', jsonData.list[i].data); } });
The above is the content of Node.js data push_node.js?1.1.2. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

How does Node.js do GC (garbage collection)? The following article will take you through it.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!
