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. });There is a problem here, that is. After the WebSocket connection and the Socket connection are established, the two connections are blocked from each other. Tomcat does not know which WebSocket connection sent the data, nor does it know which client sent the data. Of course, Node.js. You can use the session id to be sent to Tomcat to identify which client it is, but this article uses another method. When the client establishes a WebSocket connection with Node.js, each connection will contain an instance. Here it is called socketIO. Each socketIO has an id attribute to uniquely identify the connection, here it is called socket_id. Use socket_id to create a mapping table in the Node.js server to store the mapping relationship between each socketIO and socket_id. The Node.js server brings this socket_id when sending data to Tomcat, and then the Java part performs a series of processing and then encapsulates the different data required by each client and returns it. The returned data must have a corresponding relationship with the socket_id. , when the Node.js server receives the data sent by Tomcat, it is distributed to different clients through different socketIOs through the previously mentioned mapping table.
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); } });This article only gives a simple example of two such connections. Many things need to be added to the specific business. Since Node.js has been introduced into the project, the front-end needs to take on more tasks, such as data processing, caching, and even adding a lot of business logic.
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)!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),