Home  >  Article  >  Web Front-end  >  Node.js implements data push_node.js?1.1.2

Node.js implements data push_node.js?1.1.2

PHP中文网
PHP中文网Original
2016-05-16 15:05:331729browse

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:

Node.js implements data push_node.js?1.1.2

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(&#39;127.0.0.1:8181&#39;);
 // 发送数据至服务器
socket.emit(&#39;fromWebClient&#39;, jsonData);
// 从服务器接收数据
 socket.on(&#39;pushToWebClient&#39;, 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(&#39;http&#39;),
  app = http.createServer().listen(&#39;8181&#39;),
  io = require(&#39;socket.io&#39;).listen(app);
io.sockets.on(&#39;connection&#39;, function (socketIO) {
  // 从客户端接收数据
  socketIO.on(&#39;fromWebClient&#39;, function (webClientData) {
    // do sth.
  });
  // 客户端断开连接
  socketIO.on(&#39;disconnect&#39;, function () {
    console.log(&#39;DISCONNECTED FROM CLIENT&#39;);
  });    
  // 向客户端发送数据
  socketIO.emit(&#39;pushToWebClient&#39;, 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(&#39;http&#39;),
   net = require(&#39;net&#39;),
   app = http.createServer().listen(&#39;8181&#39;),
   io = require(&#39;socket.io&#39;).listen(app),
   nodeServer = new net.Socket();
 // 连接到Tomcat
 nodeServer.connect(8007, &#39;127.0.0.1&#39;, function() {
   console.log(&#39;CONNECTED&#39;);
 });
// 存储客户端的WebSocket连接实例
 var aSocket = {};
 // 同客户端建立连接
 io.sockets.on(&#39;connection&#39;, function (socketIO) {
  // 从客户端接收数据,然后发送至Tomcat
   socketIO.on(&#39;fromWebClient&#39;, function (webClientData) {    
    // 存储至映射表
     aSocket[socketIO.id] = socketIO;
    // 发送至Tomcat的数据中添加socket_id
    webClientData[&#39;sid&#39;] = socketIO.id;    
    // 发送String类型的数据至Tomcat
    nodeServer.write(JSON.stringify(webClientData));    
   });
   // 客户端断开连接
   socketIO.on(&#39;disconnect&#39;, function () {
    console.log(&#39;DISCONNECTED FROM CLIENT&#39;);
   });  
});
 // 从Tomcat接收数据
 nodeServer.on(&#39;data&#39;, function (data) { 
   var jsonData = JSON.parse(data.toString());  
   // 分发数据至客户端
   for (var i in jsonData.list) {
     aSocket[jsonData.list[i][&#39;sid&#39;]].emit(&#39;pushToWebClient&#39;, 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)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn