Translated from: Http://cloudbbs.org/forum.php?mod=viewthread&tid=28773&page=1&extra= #pid180304
First, preface
1. Comet Technology
The browser as the foreground of the WEB application, its processing function is relatively limited. The development of the browser needs the client to upgrade the software, at the same time due to the diversity of client browser software, in a sense, also affected the promotion of new browser technology. In WEB applications, the main task of a browser is to send requests, and the information returned by the parsing server is displayed in a different style. AJAX is the result of the development of browser technology, which improves the responsiveness of single-user operations by sending asynchronous requests on the browser side. But the WEB is essentially a multi-user system, and for any user, the server can be considered another user. The development of existing AJAX technology does not solve in a multi-user Web application, the updated information in real-time to the client, so that users may be "outdated" information under the operation. The application of AJAX makes it possible to update the background data more frequently.
With the development of the Internet, Web applications are endless, there are a variety of web site monitoring, real-time quotes, instant messaging system, in order to let users get a better experience, the server needs to frequently push information to the client. Developers typically use AJAX-based long polling or an IFRAME and Htmlfile-based streaming approach. Of course, some programs need to install a variety of plugins (Java applets or Flash) on the client side to support better performance "push" information.
2. Long, short connections in the HTTP protocol
The procedure for a short connection is to establish a connection--data transfer--to close the connection ... Establish connection--data transfer--close connection
The operation of the long connection is: Establish a connection-data transmission ... (Keep connected) ... Data transfer--close connection
The difference between a long connection and a short connection is that the client and server have different shutdown policies. A short connection closes a connection after a connection is made only once, and a long connection makes multiple data transfers until the connection is closed (the connection is closed in a long connection via the connection:closed header field).
Second, web communications
The first thing to figure out, XHR's readystate various states.
| Property |
Describe |
| onReadyStateChange |
The function (or function name) is called whenever the ReadyState property is changed. |
| ReadyState |
The state of being xmlhttprequest. Vary from 0 to 4.
0: Request not initialized 1: Server Connection established 2: Request received 3: In Request processing 4: The request is complete and the response is ready
|
| Status |
$: "OK" 404: Page Not Found |
1. Polling
Polling is a "pull" of the information work mode. Set a timer to ask the server for information on a timed basis, and the link will be closed each time the connection is established to transmit data.
Front-end implementations:
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's ActiveXObject ("Microsoft.XMLHTTP") supports the Get method to send data,
//Other browsers not supported, tested and verified
xhr.send (type = ="GET" ? NULL: Data);
};
Vartimer = setinterval (function(){
polling ();}, +);
In the process of polling, if the last Xhr object has not been transferred due to network reasons, the timer has already started the next query, whether the last transmission will still be in the queue, this problem I did not study. If interested can write themselves an AJAX request management queue.
2. Long polling (long-polling)
Long polling in fact there is no special place, that is, when the XHR object closes the connection immediately and then to him to see the code:
var longpoll = function (type, URL) {
var xhr = new XMLHttpRequest ();
Xhr.onreadystatechange = function () {//Status is 4, data transfer complete, 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 disconnects, the client connects immediately and does not give him a moment's rest, which is long polling.
3. Data Flow
Data flow mode, before the established connection disconnects, that is, the readystate state is 3, the time to accept the data, but the trouble is here, because the data is being transmitted, you get the xhr.response may be half the data, so, it is best to define a data transfer protocol, For example, the first 2 bytes represent the length of the string, and then you only get the length of the content, and then change the cursor position.
If the data is in the form of data Splitchar, Splitchar is the data end flag (length 1).
Then the data content of the transmission is the splitchar of the information in the database Splitchar data Splitchar ...
var dataStream = function (type, URL) {
var xhr = new XMLHttpRequest ();
Xhr.onreadystatechange = function () {
Status is 3, data is received in
if (xhr.readystate = = 3) {
var i, l, s;
s = xhr.response; Reading data
L = s.length; Get Data length
Get the data from the cursor position and split the data
s = S.slice (P, l-1). Split (Splitchar);
Cycle and manipulate data
For (i in S) if (s) deal (s);
p = l; Update cursor Position
}
Status is 4, data transfer complete, reconnect
if (xhr.readystate = = 4) {
Xhr.onreadystatechange = null;
DataStream (type, URL);
}
};
Xhr.open (type, URL, true);
Xhr.send ();
};
This code is a problem, when the readystate is 3, you can get the data, but then the data obtained may only be part of the overall data, then the half will not be taken. The readystate will not change until the data is transferred, meaning that he will not continue to accept the remaining data. We can monitor the readystate on a regular basis, as can be seen in the following example.
Such processing is not complicated, but there are problems. The above polling and long polling are supported by all browsers, so I did not write code that is compatible with IE, but here, the low version IE does not allow to read the data at ReadyState 3, so we have to implement it in other ways.
Before Ajax entered the Web topic, we already had a magic weapon, that is, the IFRAME, using the IFRAME can still get the data asynchronously, for the lower version of IE can be used to open an IFRAME to accept the data stream.
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 links
if (ifr.readystate = = "complete") {
Clearinterval (timer);
DataStream (URL);
}
}, 16);
};
};
Time to listen to the readystate of the IFRAME, so as to get the data stream, however, there is still a problem with the above processing method. Data flow implementation of the "server Push" the principle of the data, the simple point is that the document (data) has not been loaded, this time the work of the browser is to go to the server to get the data to complete the document (data) loading, we are using this, to the browser plug something past ~ So the above using the IFRAME way to obtain data , the browser will always be in the loading state, the title of the circle has been rotating, the state of the mouse is also loading, which is quite uncomfortable to see. Fortunately, IE improves the Htmlfile object, which is the equivalent of an in-memory document object, which parses documents. So we create a Htmlfile object that puts an IFRAME inside it to connect to the server. In this way, various 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 links
if (d.readystate = = "complete") {
Clearinterval (timer);
DataStream (URL);
}
}, 16);
};
};
4.websocket
WebSocket is the front end of an artifact, Ajax with so long, the relevant technology is very mature, but to achieve a data pull is really very difficult, from the code above also see, various compatibility issues, various details of the problem, since the websocket, haha, five floor on the 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 WebSocket instance, everything is OK, ws://is the WebSocket connection protocol, 8888 is the port number. The Data property is provided in OnMessage, which is quite handy.
5.EventSource
This is the eventsource that is provided in HTML5, which is an extremely concise acceptance function for server push information.
New EventSource ("test.php"). Onmessage=function (evt) {
Console.log (Evt.data);
};
Simplicity and WebSocket are the same, but there is a need to note that the test.php output of the data stream should be a special MIME type, the requirement is "Text/event-stream", if not set, you try ~ (throw the exception directly)
6.ActionScript
Love must have not considered the sixth way, although the best compatibility, if you do not understand as, out of the bug you will not debug.
Implementation method: Embedded in the HTML page a Flash program that uses the XMLSocket class. JavaScript communicates with the server-side socket interface by invoking the set of interface interfaces provided by this Flash program. JavaScript can easily control the display of the contents of an HTML page after it receives information that is sent in XML format on the server side.
7.Java Applet Socket Interface
This thing is similar to flash, but I do not understand, I will not elaborate.
Third, back-end processing mode
This article is mainly to summarize the various communication methods of JavaScript, the backend with node to deal with, it should be quite to force.
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!=connection) {
Conns.send (msg);
}
}
});
});
Server.listen (8888);
Here is a test demo for PHP.
Header (' content-type:text/html; Charset=utf-8 ');
while (1) {
echo Date (' y-m-d h:i:s ');
Flush ();
Sleep (1);
};
Four, the advantages and disadvantages of web communication methods
Polling, this method should be the least technical content, the most convenient operation, but the timeliness is not strong, the timer of the time interval set short can be slightly eased.
Long polling, is a relatively good way of web communication, but each disconnection, compared to the server resources, the client to do not matter.
Data flow, he and long polling is different is the time to accept the data, the data flow is readystate to 3 when the acceptance, low version IE is not very compatible, handling a little trouble, but also to design data transmission protocol. However, he has a considerable consumption of resources than the above.
WebSocket and EventSource, two sharp weapon, however, not a few browser support, it is more sad ~
ActionScript and Java applets, both need to install plug-ins on the client, one is Flash plug-in, one is a Java plug-in, and the front-end people are generally not familiar with this thing, if there is no better package to use the library, then the proposal is not used.
V. References
Http://www.ibm.com/developerworks/cn/web/wa-lo-comet/Comet: "Server Push" technology based on HTTP long connections
http://blog.csdn.net/yankai0219/article/details/8208776 long connection, short connection in HTTP protocol
Http://www.web-tinker.com/comet Series articles recommended subscriptions
"Go" javascript Web communication