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:
1 < src= "Static/js/socket.io.js"></script>
Client-side JavaScript code:
1 var socket = io.connect (' 127.0.0.1:8181 '); 2 // sending data to the server 3 socket.emit (' fromwebclient ', jsondata); 4 // receiving data from the server 5 function (data) {6 // Do sth. 7 });
node. JS Server Code:
1 varHTTP = require (' http '),2App = Http.createserver (). Listen (' 8181 '),3IO = require (' Socket.io '). Listen (app);4Io.sockets.on (' Connection ',function(socketio) {5 //receiving data from the client6Socketio.on (' Fromwebclient ',function(webclientdata) {7 //Do sth.8 });9 //Client DisconnectsTenSocketio.on (' Disconnect ',function () { OneConsole.log (' Disconnected from CLIENT '); A }); - //sending data to the client -Socketio.emit (' Pushtowebclient ', Jsondata); the});
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 is successful, 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 over to each client through the node. JS server.
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:
1 varHTTP = require (' http '),2NET = require (' net '),3App = Http.createserver (). Listen (' 8181 '),4IO = require (' Socket.io '). Listen (APP),5Nodeserver =NewNet. Socket ();6 //Connect to Tomcat7Nodeserver.connect (8007, ' 127.0.0.1 ',function() {8Console.log (' CONNECTED ');9 });Ten //WebSocket Connection instance of the storage client One varAsocket = {}; A //establish a connection with the client -Io.sockets.on (' Connection ',function(socketio) { - //receives data from the client and sends it to Tomcat theSocketio.on (' Fromwebclient ',function(webclientdata) { - //Save to mapping table -Asocket[socketio.id] =Socketio; - //add socket_id to data sent to Tomcat +webclientdata[' sid '] =socketio.id; - //send a string type of data to Tomcat + Nodeserver.write (Json.stringify (webclientdata)); A }); at //Client Disconnects -Socketio.on (' Disconnect ',function () { -Console.log (' Disconnected from CLIENT '); - }); - }); - in //receiving data from Tomcat -Nodeserver.on (' Data ',function(data) { to varJsondata =Json.parse (data.tostring ()); + //Distributing data to clients - for(varIinchjsondata.list) { theasocket[jsondata.list[i][' Sid ']].emit (' pushtowebclient '), jsondata.list[i].data); * } $});
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.