Web communication is a very large topic that covers a wide range of areas. Because I have recently learned some web communication knowledge in JavaScript, I will summarize it here. There should be errors in the text or unclear statements, so I hope it will correct it!
1. Preface
1. Come technology
As the front desk for web applications, the browser has relatively limited processing functions. The development of browsers requires client upgrade software. At the same time, due to the diversity of client browser software, in a sense, it has also affected the promotion of new browser technologies. In web applications, the main job of the browser is to send requests and parse the information returned by the server to display in different styles. AJAX is the result of the development of browser technology. By sending asynchronous requests on the browser side, it improves the responsiveness of single-user operations. 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 cannot solve the problem of transmitting updated information to the client in a multi-user web application in real time, so that users may operate under "outdated" information. And AJAX's application makes it possible to update background data more frequently.
With the development of the Internet, web applications are emerging one after another, and there are also various website monitoring, instant quotation, and instant messaging systems. In order to give users a better experience, the server needs to frequently push information to the client. Developers generally use AJAX-based long polling method or iframe and htmlfile-based streaming method. Of course, some programs need to install various plug-ins (Java applet or Flash) on the client to support relatively good performance "push" information.
2. Long and short connections in HTTP protocol
The operation steps of a short connection are: establish a connection - data transmission - close the connection... Establish a connection - data transmission - close the connection
The operation steps for a long connection are: establish a connection - data transmission... (keep the connection)...data transmission - close the connection
The difference between long connections and short connections is mainly because the closing strategies adopted by clients and servers are different. A short connection closes the connection only once a data transmission is made after the connection is established, while a long connection will conduct multiple data transmissions until the connection is closed (the connection is closed in the long connection through the Connection: closed header field).
2. Web communication
First of all, we need to figure out the various states of xhr's readystate.
property | describe |
---|---|
onreadystatechange | Stores a function (or function name), which is called whenever the readyState property changes. |
readyState | There is a status of XMLHttpRequest. Changes from 0 to 4. 0: The request is not initialized 1: The server connection has been established 2: The request has been received 3: The request is being processed 4: The request has been completed and the response is ready |
status | 200: "OK" 404: Page not found |
1. Investing
Polling is a working mode of "pulling" information. Set a timer to ask the server regularly whether there is information. 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; = function(){ if( == 4) { receive(); = null; } }; (type, url, true); //IE's ActiveXObject("") supports GET method to send data. //Other browsers do not support it, tested and verified (type == "GET" ? null : data); }; var timer = setInterval(function(){ polling(); }, 1000);
During the polling process, if the previous xhr object has not been transmitted due to network reasons, the timer has already started the next query. I have not studied this question whether the last transmission will still be in the queue. If you are interested, you can write ajax request management queue yourself.
2. Long-polling
There is actually nothing special about long polling, just connect it to the xhr object immediately when it closes the connection~ See the code:
var longPoll = function(type, url){ var xhr = new XMLHttpRequest(); = function(){ // Status is 4, data transmission is completed, reconnect if( == 4) { receive(); = null; longPoll(type, url); } }; (type, url, true); (); }
As long as the server is disconnected, the client will connect immediately, so that it will not have a moment of rest. This is long polling.
3. Data flow
Data flow method: before the established connection is disconnected, that is, when the readystate state is 3, the troublesome thing is also here, because the data is being transmitted, and what you get may be half of the data. Therefore, it is best to define a data transmission protocol, such as the first 2 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 is the data content, splitChar is the end of data (length is 1). Then the transmitted data content is data splitChar data splitChar data splitChar...
var dataStream = function(type, url){ var xhr = new XMLHttpRequest(); = function(){ // Status is 3, data is being received if( == 3) { var i, l, s; s = ; //Read data l = ; //Get the data length //From the cursor position to get data and use split data s = (p, l - 1).split(splitChar); //Collapse and operate data for(i in s) if(s[i]) deal(s[i]); p = l; //Update cursor position } // Status is 4, data transmission is completed, reconnect if( == 4) { = null; dataStream(type, url); } }; (type, url, true); (); };
There are problems with this code. When readystate is 3, the data can be obtained, but the data obtained at this time may only be part of the overall data, so the second half cannot be obtained. readystate will not change until the data is transferred, which means it will not continue to accept the remaining data. We can listen to readystate regularly, as you can see in the following example.
This kind of processing is not complicated, but there are problems. The above polling and long polling are supported by all browsers, so I did not write IE-compatible code, but here, the lower version of IE does not allow reading data when readystate is 3, so we must use other methods to implement it.
Before ajax entered the web topic, we already had a magic weapon, that is, iframe. Using iframes can still obtain data asynchronously. For low-version IEs, we can use iframes to accept data streams.
if(isIE){ var dataStream = function(url){ var ifr = ("iframe"), doc, timer; = url; (ifr); doc = ; timer = setInterval(function(){ if( == "interactive"){ // Process data, same as above } // Re-create the link if( == "complete"){ clearInterval(timer); dataStream(url); } }, 16); }; };
Regularly listen to the changes in the iframe's readystate to obtain the data flow, but the above processing method still has problems. What is the principle of data streaming to implement "server push" data? To put it simply, the document (data) has not been loaded yet. At this time, the browser's job is to go to the server to get data to complete the document (data) loading. We use this to stuff something to the browser~ Therefore, the above method of obtaining data using iframe will keep the browser in the loading state, the circle on the title is constantly turning, and the mouse state is also loading, which looks quite unpleasant. Fortunately, IE provides an HTMLFile object, which is equivalent to a Document object in memory, which parses the document. So we create an HTMLFile object and place an IFRAME inside to connect to the server. In this way, all browsers will support it.
if(isIE){ var dataStream = function(url){ var doc = new ActiveXObject("HTMLFile"), ifr = ("iframe"), timer, d; ("<body/>"); = url; (ifr); d = ; timer = setInterval(function(){ if( == "interactive"){ // Process data, same as above } // Re-create the link if( == "complete"){ clearInterval(timer); dataStream(url); } }, 16); }; };
websocket is a front-end artifact. Ajax has been used for so long and the related technologies are very mature. However, it is really difficult to pull data. I also see from the above code that various compatibility issues and various details processing issues. Since the websocket has been used, haha, I went to the fifth floor in one go...
var ws = new WebSocket("ws://:8888"); = function(evt){}; = function(evt){ deal(); }; = function(evt){}; //();
Create a new WebSocket instance and everything is OK. ws:// is the connection protocol of websocket, and 8888 is the port number. The data attribute is provided in onmessage, which is quite convenient
The EventSource thing provided in HTML5 is an extremely concise server push information acceptance function.
new EventSource("").onmessage=function(evt){ (); };
The simplicity is the same as the websocket, but there is a point to pay attention to here. The output data stream should be of a special MIME type, and the requirement is "text/event-stream". If not set, try it~ (throw the exception directly)
If you have no choice, don't consider this sixth method. Although the compatibility is the best, if you don't understand as, you won't debug if there is a bug.
Specific implementation method: Embed a Flash program using the XMLSocket class in the HTML page. JavaScript communicates with the socket interface on the server side by calling the socket interface provided by this Flash program. JavaScript can easily control the content display of HTML pages after receiving the information transmitted in XML format on the server side.
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 method
This article mainly summarizes various communication methods of Javascript. The backend and node are handled, which should be quite powerful.
var conns = new Array(); var ws = require("websocket-server"); var server = (); ("connection", function(connection){ ("Connection request on Websocket-Server"); (connection); ('message',function(msg){ (msg); for(var i=0; i<; i++){ if(conns[i]!=connection){ conns[i].send(msg); } } }); }); (8888);
Below is a php test demo.
header('Content-Type:text/html; charset=utf-8'); while(1){ echo date('Y-m-d H:i:s'); flush(); sleep(1); };
4. Analysis of the pros and cons of web communication methods
- Polling, this method should be the least technical and most convenient to operate, but it is not timely. Setting the timer interval time shorter can be slightly alleviated.
- Long polling is a relatively good web communication method, but every time you disconnect, it consumes server resources, so it doesn't matter if the client is.
- The difference between data flow and long polling is that it accepts data differently. The data flow is accepted when readystate is 3. The low version of IE is not very compatible, which is a little troublesome to process. And you also have to design your own data transmission protocol. However, his consumption of resources is considerable than the above.
- Websocket and EventSource are two powerful tools, but few browsers support it, which is quite sad~
- ActionScript and Java Applet both require plug-ins to be installed on the client side, one is the Flash plug-in and the other is the Java plug-in. People who work on the front end are generally not familiar with this thing. If there is no better encapsulation library to use, it is recommended not to use it.
V. Reference materials
/developerworks/cn/web/wa-lo-comet/ Comet: "Server push" technology based on HTTP long connections
/yankai0219/article/details/8208776HTTP protocol medium-long connection and short connection
/Comet series of articles
This is the end of this article about the detailed explanation of JavaScript's method of implementing communication with web. For more related JavaScript and web communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!