Using node. js for data push

Source: Internet
Author: User
Tags emit session id string format

Business scenario: Back-end update data is pushed to the client (the Java section uses the Tomcat server).

There are many solutions for back-end push data, such as polling, Comet, WebSocket.

1. Polling is the lowest development cost for the backend, which is to process the AJAX request and return the data in the traditional way , while in school the lab's project has always been polled because it is the most insured and easiest to implement. However, the waste of the communication resources caused by polling cannot be ignored, and the request and response are sent as usual, regardless of whether the data changes, and each HTTP request carries a long header message.

2. The concept of comet is a long connection, after the client sends the request, the backend will keep the connection down until the connection times out or the backend returns data and then reestablish the connection, effectively transferring the communication resources to the server and actually consuming the server resources.

3. WebSocket is a full-duplex communication technology provided by HTML5, through the "handshake" to achieve client-server communication, real-time, carrying a smaller head, currently supported by the following browsers:

The ideal scenario is to take websocket and comet in a way that IE8 and other browsers take comet mode and do downgrade processing. But that way, the backend needs to implement two logic for processing the request, websocket and comet. So, this article joins node. JS and is doing this by transferring the logic of processing websocket (or Comet) to the node. js section, without "trouble" for the backend, because in practice it is not easy for front-end developers to push back-end developers. node. JS is the middle tier in which the browser communicates with the Java business Logic layer, connecting the client with Tomcat, and communicating with Tomcat via the socket (socket, not websocket, the backend needs to implement the socket interface.

On the client side, WebSocket and comet are implemented through Socket.io, Socket.io will choose the appropriate implementation for different browser versions or different clients (WebSocket, long pull. ), the introduction of Socket.io makes it easy to handle websocket (or long connections). Socket.io

The client introduces Socket.io:

<src= "static/js/socket.io.js"></script>    

Client-side JavaScript code:

var socket = io.connect (' 127.0.0.1:8181 ');  send data to Server 3 socket.emit (' fromwebclient ', jsondata);  receives data function {//do sth from the server.  7});           

node. JS Server Code:

1var http = require (' http '),2 app = Http.createserver (). Listen (' 8181 '),3 IO = require (' Socket.io '). Listen (app);4 Io.sockets.on (' Connection ',function(Socketio) {5//Receiving data from the client6 Socketio.on (' Fromwebclient ',function(Webclientdata) { 7 // do Sth. 8 });  9 // client disconnects 10 socketio.on (' Disconnect ', function () {11 Console.log (' Disconnected from CLIENT ' }); 13 // send data to the client 14 socketio.emit (' pushtowebclient ' , Jsondata); 15});             

Establishing a client connection to the node. JS server is only the first step, and the following need to establish a link between the node. JS server and the Java business Logic layer. At this point, the node. JS server sends a TCP connection request to Tomcat as the client. After the connection succeeds, the node. JS Server and Tomcat establish a full-duplex channel and are the only one that forwards from the node. JS server to Tomcat, regardless of the number of client requests, as well as the data that Tomcat pushes through the node. JS Server distributed to individual clients.

One problem here is that after the WebSocket connection is established with the socket connection, two connections are shielded from each other. Tomcat does not know which data the WebSocket connection sends over, or which client sends the data. Of course, node. JS can use the session ID to send to Tomcat to identify which client it is, but this article uses a different approach.

When a client establishes a WebSocket connection with node. js, each connection contains an instance, which is referred to as socketio. Each socketio has an id attribute to uniquely identify the connection, which is called socket_id. With socket_id, a mapping table is established on the node. JS server to store each socketio and socket_id mapping relationship. The node. JS server sends the data to Tomcat with this socket_id, and after a series of processing by the Java section, the different data required by each client is packaged and returned with the corresponding relationship to the socket_id in the returned data. This way, when the node. JS server receives data from Tomcat, it is distributed to different clients by different socketio by the previously mentioned mapping table.

node. JS Server Code:

1var http = require (' http '),2 net = require (' net '),3 app = Http.createserver (). Listen (' 8181 '),4 IO = require (' Socket.io '). Listen (APP),5 Nodeserver =NewNet. Socket ();6//Connect to Tomcat7 Nodeserver.connect (8007, ' 127.0.0.1 ',function() {8 Console.log (' CONNECTED ');9});10//WebSocket connection instance of the storage client11var asocket ={};12//Establish a connection with the clientIo.sockets.on (' Connection ',function(Socketio) {14//Receives data from the client and sends it to TomcatSocketio.on (' Fromwebclient ',function(Webclientdata) {16//Save to mapping tableAsocket[socketio.id] =Socketio;18//Add socket_id to data sent to Tomcatwebclientdata[' sid '] =Socketio.id;20//Send a string type of data to Tomcat21stNodeserver.write (Json.stringify (webclientdata));22});23//Client DisconnectsSocketio.on (' Disconnect ',function() {Console.log (' Disconnected from CLIENT ');26});27});2829// receive data from Tomcat 30 nodeserver.on (' data ', function31  Json.parse (data.tostring ()); 32 // Distribute data to client 33 for (var i in Jsondata.list) {34 asocket[jsondata.list[i][' Sid ']].emit (' pushtowebclient ' , Jsondata.list[i].data); 35 }36});    

The above code omits some logic, such as the data that the node. JS server receives from Tomcat is divided into two kinds, one is push data, the other is the data that responds to the request, the data that pushes over is processed uniformly here.

When communication is processed, the data that node. JS sends to Tomcat is in string format, and the data received from Tomcat is a buffer object (8 binary), which needs to be converted to a string before being converted to JSON for sending to the client.

This article just gives a simple example of such two connections, which involves a lot of things in a particular business. Now that you've introduced node. js into your project, you need to take on more things from the front end, such as handling data, caching, and even adding a lot of business logic.

Using node. js for data push

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.