JavaScript web communication 2013-12-1722: 01 byBarretLee, 259 reading, 2 comments, favorites, editing web communication, a very large topic, also involves a wide range. Because I recently learned some web communication knowledge in javascript, I would like to summarize it here .... SyntaxHighlighter. JavaScript web communication by BarretLee, 259 reading, 2 comments, favorites, edit web communication, a particularly large topic, which involves a wide range of topics. Because I recently learned some web communication knowledge in javascript, I would like to summarize it here. There should be some misunderstandings or unclear descriptions in this article, and I hope you can make an axe! I. Preface 1. As the front-end of Web applications, the comet technology browser has limited processing functions. Browser development requires upgrading the client software. Due to the diversity of client browser software, it also affects the promotion of new browser technologies. In Web applications, the main task of a browser is to send a request and parse the information returned by the server in different styles. AJAX is the result of the development of browser technology. By sending asynchronous requests on the browser side, the responsiveness of single-user operations is improved. However, Web is essentially a multi-user system. 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 real time in a multi-user Web application, so that users may perform operations under "obsolete" information. The Application of AJAX makes it possible to update background data more frequently. With the development of the Internet, there are endless web applications, and there are also various website monitoring, instant quotes, 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 or iframe and htmlfile-based stream processing. Of course, some programs need to install various plug-ins (Java applet or Flash) on the client to support "pushing" information with good performance. 2. in the HTTP protocol, the procedure for creating a short connection is: establish a connection -- data transmission -- close the connection... to establish a connection-data transmission-to close a persistent connection, follow these steps: establish a connection-data transmission... (keep connection )... data transmission-the difference between closing a persistent connection and a short connection is that the closing policies adopted by the client and server are different. After a connection is established, the connection is closed after only one data transmission is performed, the persistent Connection will transmit data multiple times after the Connection is established until the Connection is closed (the Connection is closed through the Connection: closed header field in the persistent Connection ). 2. web communication should first clarify the readystate status of xhr. The onreadystatechange storage function (or function name). This function is called whenever the readyState attribute changes. ReadyState has the XMLHttpRequest status. Changes from 0 to 4. 0: request not initialized 1: server connection established 2: request received 3: Request Processing in progress 4: request completed and response ready status 200: "OK" 404: page 1 not found. round Robin is a kind of work mode for pulling information. Set a timer to regularly check whether the server has information. After a connection is established to transmit data, the link is 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); // ActiveXObject ("Microsoft. XMLHTTP ") supports the GET method to send data, // not supported by other browsers. xhr has been tested and verified. send (type = "GET "? Null: data) ;}; var timer = setInterval (function () {polling () ;}, 1000, as a result, the previous xhr object has not been transmitted, and the timer has started the next query to check whether the last transmission is still in the queue. I have not studied this problem. If you are interested, you can write an ajax request management queue. 2. long-polling (long-polling) is actually nothing special, that is, when the xhr object closes the connection, it will be immediately connected to him ~ Code: var longPoll = function (type, url) {var xhr = new XMLHttpRequest (); xhr. onreadystatechange = function () {// The status is 4. After data transmission is 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 is disconnected, the client will be connected immediately without a moment of rest. This is long polling. 3. the data stream mode accepts data before the established connection is disconnected, that is, when the readystate is 3, but the trouble is also found here because the data is being transmitted and the xhr you get. response may be half-cut data. Therefore, it is best to define a data transmission protocol. For example, the first two bytes indicate the length of the string, and then you only get the content of this length, then change the cursor position. If the data format is: data splitChar data is the data content, and splitChar is the end mark of the data (the length is 1 ). The transmitted data content is data splitChar... var dataStream = function (type, url) {var xhr = new XMLHttpRequest (); xhr. onreadystatechange = function () {// The status is 3. if (xhr. readyState = 3) {var I, l, s; s = xhr. response; // read data l = s. length; // obtain the Data length // obtain the data starting from the cursor position and use the split data s = s. slice (p, l-1 ). split (splitChar); // cyclically operate the data for (I in s) if (s [I]) deal (s [I]); p = l; // update the cursor position} // The status is 4, count After data transmission is complete, reconnect if (xhr. readyState = 4) {xhr. onreadystatechange = null; dataStream (type, url) ;}}; xhr. open (type, url, true); xhr. send () ;}; the code is written incorrectly. When the readystate is 3, data can be obtained. However, the obtained data may only be part of the overall data, the last half won't be available. Readystate will not change before the data transmission is completed, that is, it will not continue to accept the remaining data. We can regularly listen to readystate, as shown in the following example. This process is not complicated, but there are problems. The preceding Round Robin and long polling are supported by all browsers, so I didn't write code compatible with IE. However, earlier IE versions cannot read data when readystate is 3, therefore, we must adopt other methods. Before ajax becomes a web Topic, we already have a magic weapon, namely, iframe. iframe can also be used to obtain data asynchronously. For earlier versions of IE, iframe can be used to open and accept data streams. If (isIE) {var dataStream = function (url) {var ifr = document. createElement ("iframe"), doc, timer; ifr. src = url; document. body. appendChild (ifr); doc = ifr.content1_doc ument; timer = setInterval (function () {if (ifr. readyState = "interactive") {// process data, same as above} // re-establish the link if (ifr. readyState = "complete") {clearInterval (timer); dataStream (url) ;}, 16) ;}; regularly listens for changes in the readystate of iframe, to obtain the data stream. However There is still a problem with the method. What is the principle of implementing "server push" data for data streams? Simply put, documents (data) have not been fully loaded yet, in this case, the work of the browser is to take data from the server to load the document (data). We use this to plug something into the browser ~ Therefore, the above use of iframe to obtain data will keep the browser loading, the circle on the title is always rotating, And the mouse is also loading, which looks quite uncomfortable. Fortunately, IE improves the HTMLFile object, which is equivalent to a Document object in memory, which parses the Document. Therefore, we create an HTMLFile object and place an IFRAME in it to connect to the server. In this way, all types of browsers are supported. If (isIE) {var dataStream = function (url) {var doc = new ActiveXObject ("HTMLFile"), ifr = doc. createElement ("iframe"), timer, d; doc. write (""); Ifr. src = url; doc. body. appendChild (ifr); d = ifr.content1_doc ument; timer = setInterval (function () {if (d. readyState = "interactive") {// process data, same as above} // re-establish the link if (d. readyState = "complete") {clearInterval (timer); dataStream (url) ;}, 16) ;}; 4. websocket is a front-end artifact. After ajax has been used for so long, the related technologies are also very mature. However, it is very difficult to pull individual data, as shown in the code above, various compatibility issues, various details to deal with problems, since the websocket, haha, one breath on the fifth floor... 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 WebSocket instance, and everything will be OK. ws: // is the websocket connection protocol. Port 8888 is the port number. Onmessage provides the data attribute, which is quite convenient. 5. EventSource HTML5 provides EventSource, which is a very simple receiving function for server push information. New EventSource ("test. php "). onmessage = function (evt) {console. log (evt. data) ;}; the degree of conciseness is the same as that of websocket, but here is a note, test. the data stream output by php should be of a special MIME type, which must be "text/event-stream". If not set, try ~ (Directly throw an exception) 6. If you do not have to consider the sixth method, you won't debug it even if you don't understand the. Implementation Method: embed a Flash program using the XMLSocket class in the HTML page. JavaScript calls the set interface provided by the Flash program to communicate with the set interface of the server. After receiving information transmitted by the server in XML format, JavaScript can easily control the display of HTML page content. 7. The principle of Java Applet set interface is similar to that of Flash, but I don't understand it. Iii. backend Processing Methods this article mainly summarizes various communication methods of Javascript. the backend should work with node for processing, which should be awesome. 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
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.