Detailed Explanation of Communication Method between JavaScript and web

  • 2021-08-06 20:03:27
  • OfStack

web communication, a particularly large topic, also covers a wide range. Because I recently learned some web communication knowledge in javascript, I will summarize it here. There should be some misunderstandings or unclear expressions in the text, and I hope to correct them!

1. Preface

1. comet Technology

As the foreground of Web application, the browser has limited processing functions. The development of the browser requires the client to upgrade the software. At the same time, due to the diversity of the client browser software, in a sense, it also affects the promotion of new browser technology. In the Web application, the main job of the browser is to send requests, and the information returned by the parsing server is displayed in different styles. AJAX is the result of the development of browser technology, which improves the responsiveness of single-user operation by sending asynchronous requests on the browser side. However, Web is essentially a multi-user system, and for any user, the server can be considered another user. The development of existing AJAX technology can not solve the problem that in a multi-user Web application, the updated information is transmitted to the client in real time, so that the user may operate under the "outdated" information. The application of AJAX makes it possible to update background data more frequently.

With the development of the Internet, web applications emerge one after another, and there are also various website monitoring, instant quotation and instant messaging systems. In order to make users get a better experience, the server needs to push information frequently to the client. Developer 1 will generally adopt the long polling mode based on AJAX or the streaming mode based on iframe and htmlfile. Of course, some programs need to install various plug-ins (Java, applet or Flash) on the client to support "push" information with good performance.

2. Long and short connections in HTTP protocol

The operation steps of short connection are: establish connection-transfer data-close connection... establish connection-transfer data-close connection
The operation steps of a long connection are: establish a connection-transfer data... (keep the connection)... transfer data-close the connection

The difference between long connection and short connection mainly lies in the different closing strategies adopted by client and server. Short connections close the connection after only one data transfer after the connection is established, while long connections close the connection after the connection is established by multiple data transfers until the connection is closed (in long connections, the connection is closed through the Connection: closed header field).

2. web Communications

First of all, we should find out the various states of readystate of xhr.

属性 描述
onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status 200: "OK"
404: 未找到页面

1. Polling

Polling is a working mode of "pulling" information. Set a timer to ask the server if there is information regularly. After each connection is established to transmit data, the link will be closed.

Front-end implementation:


var polling = function(url, type, data){
  var xhr = new XMLHttpRequest(), 
    type = type || "GET",
    data = data || null;

  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4) {
      receive(xhr.responseText);
      xhr.onreadystatechange = null;
    }
  };

  xhr.open(type, url, true);
  //IE Adj. ActiveXObject("Microsoft.XMLHTTP") Support GET Method to send data, 
  // Not supported by other browsers, tested and verified 
  xhr.send(type == "GET" ? null : data);
};

var timer = setInterval(function(){
  polling();
}, 1000);

In the process of polling, if the last xhr object has not been transmitted due to network reasons, the timer has started the next inquiry, and I have not studied whether the last transmission will still be in the queue. If you are interested, you can write a request management queue of ajax yourself.

2. Long polling (long-polling)

In fact, there is nothing special about long polling, that is, when the xhr object closes the connection, it immediately connects him to see the code:


var longPoll = function(type, url){
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function(){
    //  Status is  4 After data transfer, reconnect 
    if(xhr.readyState == 4) {
      receive(xhr.responseText);
      xhr.onreadystatechange = null;

      longPoll(type, url);
    }
  };

  xhr.open(type, url, true);
  xhr.send();
}

As long as the server is disconnected, the client connects immediately without giving him a moment's rest time, which is long polling.

3. Data flow

Data flow mode, Before the established connection is disconnected, That is, when the readystate status is 3, the data is accepted, but the trouble is also here. Because the data is being transmitted, the xhr. response you get may be half of the data. Therefore, it is best to define a data transmission protocol, for example, the first two bytes represent the length of the string, and then you only get the content of this length, and then change the position of the cursor.

If the data format is: data splitChar data for data content, splitChar for data end flag (length 1). Then the transmitted data content is data splitChar data splitChar data splitChar...


var dataStream = function(type, url){
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function(){

    //  Status is  3 In the process of receiving data 
    if(xhr.readyState == 3) {
      var i, l, s;

      s = xhr.response; // Read data 
      l = s.length;   // Get data length 

      // Get data from the cursor position and use the split data 
      s = s.slice(p, l - 1).split(splitChar);

      // Loop and manipulate data 
      for(i in s) if(s[i]) deal(s[i]);

      p = l; // Update cursor position 

    }

    //  Status is  4 After data transfer, reconnect 
    if(xhr.readyState == 4) {
      xhr.onreadystatechange = null;

      dataStream(type, url);
    }
  };

  xhr.open(type, url, true);
  xhr.send();
};

There is a problem with this code. When readystate is 3, data can be obtained, but the data obtained at this time may only be one part of the overall data, and the latter half will not be available. readystate will not change until the data transfer is completed, which means that it will not continue to accept the rest of the data. We can monitor readystate regularly, as can be seen in the following example.

This treatment is not complicated, but there are problems. The above polling and long polling are supported by all browsers, so I didn't write code compatible with IE, but here, the lower version of IE doesn't allow reading data when readystate is 3, so we must use other methods to achieve it.

Before ajax entered the topic of web, we already had a magic weapon, that is, iframe, which can still obtain data asynchronously with iframe, and can use iframe to accept data stream for lower version IE.


if(isIE){
  var dataStream = function(url){
    var ifr = document.createElement("iframe"), doc, timer;

    ifr.src = url;
    document.body.appendChild(ifr);

    doc = ifr.contentWindow.document;

    timer = setInterval(function(){

      if(ifr.readyState == "interactive"){
        //  Processing data, ibid. 
      }

      //  Re-establish a link 
      if(ifr.readyState == "complete"){
        clearInterval(timer);

        dataStream(url);
      }
    }, 16);
  };
};

Monitor the change of readystate of iframe regularly, so as to obtain data stream. However, there are still problems in the above processing mode. What is the principle of data flow to realize "server push" data, To put it simply, That is, the document (data) has not been loaded yet, At this time, the browser's job is to go to the server to get the data to complete the document (data) loading. We just use this to plug something into the browser ~ Therefore, the above-mentioned method of using iframe to obtain data will make browser 1 in the loading state, the circle 1 on title is rotating directly, and the mouse state is loading, which looks quite uncomfortable. Fortunately, IE provides the HTMLFile object, which is equivalent to an in-memory Document object and parses the document. So we create an HTMLFile object and place an IFRAME inside to connect to the server. In this way, all kinds of browsers are supported.


if(isIE){
  var dataStream = function(url){
    var doc = new ActiveXObject("HTMLFile"), 
      ifr = doc.createElement("iframe"), 
      timer, d;

    doc.write("<body/>");

    ifr.src = url;
    doc.body.appendChild(ifr);

    d = ifr.contentWindow.document;

    timer = setInterval(function(){

      if(d.readyState == "interactive"){
        //  Processing data, ibid. 
      }

      //  Re-establish a link 
      if(d.readyState == "complete"){
        clearInterval(timer);

        dataStream(url);
      }
    }, 16);
  };
};

4.websocket

websocket is an artifact at the front end. ajax has been used for so long, and the related technology is also very mature. However, it is not easy to pull 10 points of data. From the above code, we can also see all kinds of compatibility problems and all kinds of details. Since websocket, haha, I went to the 5th floor in one breath...


var ws = new WebSocket("ws://www.example.com:8888");

ws.onopen = function(evt){};
ws.onmessage = function(evt){
  deal(evt.data);
};
ws.onclose = function(evt){};

//ws.close();

Create a new instance of WebSocket, 1 is OK, ws://is the connection protocol of websocket, and 8888 is the port number. The property data is provided in onmessage, which is quite convenient

5.EventSource

EventSource is provided in HTML5, which is a very simple acceptance function of server push information.


new EventSource("test.php").onmessage=function(evt){
  console.log(evt.data);
};

Simplicity and websocket is the same, but there is a place to pay attention to, test. php output data stream should be a special MIME type, the requirement is "text/event-stream", if not set, you try ~ (throw an exception directly)

6.ActionScript

Don't consider this sixth way if you have to. Although the compatibility is the best, if you don't understand as, you won't debug it if you have a little bug.

Specific implementation method: Embedding an Flash program using XMLSocket class in HTML page. JavaScript communicates with the server-side socket by calling the socket interface provided by the Flash program. JavaScript can easily control the content display of HTML pages after receiving the information transmitted by the server in XML format.

7. Java Applet socket

The principle of this thing is similar to Flash, but I don't understand it, so I won't go into details.

3. Back-end processing

This paper mainly summarizes various communication modes of Javascript, and the back-end cooperates with node to deal with it, which should be quite powerful.


var conns = new Array();

var ws = require("websocket-server");
var server = ws.createServer();

server.addListener("connection", function(connection){
 console.log("Connection request on Websocket-Server");
 conns.push(connection);
 connection.addListener('message',function(msg){
    console.log(msg);
    for(var i=0; i<conns.length; i++){
      if(conns[i]!=connection){
        conns[i].send(msg);
      }
    }
  });
});
server.listen(8888);

The following is a test demo for an php.


header('Content-Type:text/html; charset=utf-8');
while(1){
  echo date('Y-m-d H:i:s');
  flush();
  sleep(1);
};

4. Analysis of advantages and disadvantages of web communication mode

Polling, this way should be the most technical content, the most convenient to operate, but the timeliness is not strong, the timer interval set shorter than 1 can be slightly eased. Long polling is a relatively good one web communication, but every time you disconnect, it consumes server resources, and it doesn't matter if the client goes to it. The difference between data stream and long polling is that the time to accept data is different. The data stream is accepted when readystate is 3. The lower version of IE is not compatible, so it is a little troublesome to deal with it, and it is necessary to design its own data transmission protocol. However, his consumption of resources is considerable than the above. websocket and EventSource, two sharp tools, however, few browsers support it, which is more sad ~ ActionScript and Java Applet, both of which need to install plug-ins on the client, one is Flash plug-in and one is Java plug-in, and people who engage in front-end are not familiar with this thing. If there is no better encapsulation library to use, it is recommended not to use it.

5. References

http://www.ibm.com/developerworks/cn/web/wa-lo-comet/Comet: "Server push" technology based on HTTP long connection

Long connection and short connection in http://blog.csdn.net/yankai0219/article/details/8208776 HTTP protocol

http://www.web-tinker.com/comet Series


Related articles: