Node. js implements data push _ node. js? 1.1.2

Source: Internet
Author: User
This article mainly introduces Node in detail. if you are interested in js data push, refer to the following scenario: backend update data is pushed to the client (Tomcat server is used in Java ).

There are many solutions for pushing data at the backend, such as polling, Comet, and WebSocket.

1. polling is the lowest development cost for the backend, that is, processing Ajax requests and returning data in the traditional way. during school time, lab projects always adopt polling, because it is the safest and easiest to implement. However, the communication resource waste caused by polling cannot be ignored. no matter whether the data changes or not, requests are sent and responded as usual, and each HTTP request carries a long header information.

2. the concept of Comet is a persistent connection. After a client sends a request, the backend maintains the connection until the connection times out or the backend returns data, it effectively transfers communication resources to the server, which actually consumes server resources.

3. webSocket is a full-duplex communication technology provided by HTML5. It uses a "handshake" to implement communication between the client and the server. The real-time performance is good and the header carried is small. Currently, the supported browsers are as follows:

Client JavaScript code:

Var socket = io. connect ('2017. 0.0.1: 8181 '); // send data to the server socket. emit ('fromwebclient', jsonData); // receives data from the server socket. on ('pushtowebclient', function (data) {// do something .});

Node. js server code:

Var http = require ('http'), app = http. createServer (). listen ('20140901'), io = require ('socket. io '). listen (app); io. sockets. on ('connection', function (socketIO) {// receives socketIO data from the client. on ('fromwebclient', function (webClientData) {// do something .}); // disconnect socketIO from the client. on ('disconnect', function () {console. log ('disconnectedfrom client');}); // send socketIO data to the CLIENT. emit ('pushtowebclient', jsonData );});


Establishing a connection between the client and the Node. js server is only the first step. Next we need to establish a connection between the Node. js server and the Java business logic layer. In this case, the Node. js server serves as a client and sends a TCP connection request to Tomcat. After the connection is successful, Node. the js server and Tomcat have established a full-duplex channel and are the only one. No matter how many client requests there are. the js server forwards data to Tomcat. Similarly, the data pushed by Tomcat is also forwarded through Node. the js server is distributed to various clients.

There is a problem here, that is, after both 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 or which client sent the data. Of course, Node. js can send session IDs to Tomcat to identify which client is used, but this article uses another method.

When a client establishes a WebSocket connection with Node. js, each connection contains an instance called socketIO. Each socketIO has an id attribute to uniquely identify the connection. It is called socket_id here. Use socket_id to create a ing table on the Node. js server to store the ing between each socketIO and socket_id. Node. when the js server sends data to Tomcat, it carries the socket_id. After a series of processing by Java, it encapsulates the different data required by each client and returns it together, the returned data must have a socket_id relationship. In this way, when the Node. js server receives data from Tomcat, different socketIO files are distributed to different clients through the aforementioned ing table.

Node. js server code:

Var http = require ('http'), net = require ('net'), app = http. createServer (). listen ('20140901'), io = require ('socket. io '). listen (app), nodeServer = new net. socket (); // connect to Tomcat nodeServer. connect (8007, '2017. 0.0.1 ', function () {console. log ('connected') ;}); // stores the client's WebSocket connection instance var aSocket ={}; // establishes a connection io with the client. sockets. on ('connection', function (socketIO) {// receives data from the client and sends it to Tomcat socketIO. on ('fromwebclient', function (webClientData) {// store it to the ing table aSocket [socketIO. id] = socketIO; // Add socket_id webClientData ['sid '] = socketIO to the data sent to Tomcat. id; // send data of String type to Tomcat nodeServer. write (JSON. stringify (webClientData);}); // disconnect socketIO from the client. on ('disconnect', function () {console. log ('disconnectedfrom client');}) ;}); // receives data FROM nodeServer in Tomcat. on ('data', function (data) {var jsonData = JSON. parse (data. toString (); // distribute data to the client for (var I in jsonData. list) {aSocket [jsonData. list [I] ['sid ']. emit ('pushtowebclient', jsonData. list [I]. data );}});

The above Code omitted some logic, such as Node. the js server receives data from Tomcat in two ways: Push data and Response Request data. The pushed data is processed in a unified manner.

Node. the data sent by js to Tomcat is in String format, while the data received from Tomcat is a Buffer object (in octal format), which needs to be converted to String and then converted to json and sent to the client.

This article only provides a simple example of two such connections. Many things need to be added to a specific business. Since Node. js is introduced in the project, the front-end needs to handle more things, such as data processing, caching, and even adding a lot of business logic.

The above is Node. js to implement data push _ node. js? For more information about 1.1.2, see PHP Chinese website (www.php1.cn )!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.