Core secrets of Ajax push technology

Source: Internet
Author: User
Tags html header
Core secrets of Ajax push technology (reprinted)

Core secrets of Ajax push technology

Introduction
Today, with the popularity of Web applications, users are beginning to migrate more key applications to the Web. The majority of Web application developers and promoters are enjoying the joy of success. At the same time, many users have begun to complain that our web applications are always so passive and slow. When can they make their applications more active and real-time, so that they can be notified immediately of events on the server. However, developers have to face the fact that they cannot further improve the real-time performance of applications under the inherent stateless and non-connection constraints of the web.
The development in recent years, especially the emergence of aajx, has helped our web applications to find new endpoints. However, this still does not solve the problems mentioned above. Is it true that we have no way to go?
After my exploration, I found that we can implement real-time active web-based notifications, that is, using Ajax push technology, which gives our web applications unprecedented exciting features and user experience. I will use this article to guide you through this exciting experience. The author's goal is also very simple, with the aim of providing more reference materials for everyone, whether it is right or wrong, I hope this article can play a role. it would be a great honor to have a broader discussion on the web real-time push notification technology!

Broad Prospects of Ajax push
The author divides the notification technology into two concepts: passive pull notification technology and active push notification technology. There are already a large number of articles on the internet for these two statements. I will only give a brief introduction here:
1. the passive pull notification technology is also called the pull method, as shown in figure

Browser

Server

Internet

Timed request

Response based on request
Figure: Pull Mode
The pull mode requires the client to check the server from time to determine whether a new event or data has changed. This method is not real-time, but is easier to implement on the web.
2. The active push notification technology is also called the push method, as shown in figure
Browser

Server

Internet

Active event sending

Establish a communication connection for the first time

Event
Figure: Push mode
After a connection is established between the push client and the service, the client is notified whenever a special event occurs on the server. This method is very real-time, but it is complicated to implement on the web.

The latter has significant advantages, while Ajax push is the communication technology of the latter that needs to be implemented on the Web. If Ajax push can be perfectly implemented, so Web-based IM software, Web-based key business alarm systems, Web-based Real-time Monitoring Systems, more intelligent web information systems, and even web-based remote control systems. all can be implemented, at the same time, the client deployment and installation are completely eliminated to avoid high load on the server. Many of the systems such as webmsn and Gmail are considered incredible features and can be easily developed by any web programmer. What a wonderful moment is worth looking forward.

Break through the limitations of ideas
Web applications are easy to deploy, but the Web is stateless and non-connected. From this perspective, the server cannot push notifications to the client in real time, some may say "Ignore" to me. Isn't there already many systems that have implemented web notifications? In fact, there are basically two methods to summarize the current technology for implementing dynamic Web notifications:
1. Regular refresh method. The periodic refresh method can be divided into two methods: the overall page interval refresh and the asynchronous interval refresh.
A) The overall page interval refresh method, which is used in early chat rooms. The implementation is very simple. You only need to add the following code to the HTML header:
<Meta HTTP-EQUIV = "refresh" content = "10" url = "your page">
This method is rarely used at present, mainly because if the current webpage is too complicated to load for a long time, frequent refreshes will cause a very poor user experience, at the same time, the transmission of a large amount of repeated network data will undoubtedly increase the burden on servers and networks.
B) asynchronous interval refresh method. Due to the asynchronous refresh method, even if the refreshing is normal, the page will not flash, and unnecessary data presentation is reduced. Currently, many methods are used, the implementation is divided into Ajax refresh, that is, XMLHTTP refresh and hidden Taobao refresh. The following is a simple example:
Ajax refresh
VaR XMLHTTP = new activexobject ("msxml2.xmlhttp. 5.0 ");
Function refreshui ()
{
XMLHTTP. Open ("Post", "page on which you receive requests", true );
XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded; charset = UTF-8 ");
XMLHTTP. Send (the data you submit );
VaR S = XMLHTTP. responsetext; // get the data received by the server
Updateui (s); // update data on your interface
}
Setinterval (refreshui, 20 );
The service segment can be a server processing program, such as JSP, ASP, serverlet, aspx, and so on, and then output the required data to the client through the response object.
Hide Taobao refresh
That is, put a hidden frameset or IFRAME on the page, and then obtain the data through the commit operation of the Trojan and refresh the page.
Function refreshui ()
{
VaR hiddenform = document.frames[12.16.doc ument. Forms [0]; // obtain the form information in the hidden folder.
Hiddenform. Submit (); // submit the form
Updateui (hiddenform); // updates the interface

}
Setinterval (refreshui, 20 );
However, after the regular refresh method is adopted, both Ajax commit and hidden commit share the same disadvantage: they are not updated in real time, and the refresh speed cannot be too fast. Otherwise, the performance of the client or server will be seriously affected, at the same time, the data of many customers will not be updated for a long period of time. This will cause a lot of meaningless refreshes and increase the server load. However, this method is simple, so a large number of Web applications use this method to implement notification technology, which is a non-real-time pull (passive) Notification technology.
2. Client plug-ins are embedded into the client webpage by writing third-party plug-ins for the client segment, and then establishing communication connections with the server to implement instant notification technology, this technology can implement the active push notification technology from the server to the client. Currently, it mainly provides plug-ins through ActiveX or Java applet. The disadvantage is that the implementation technology is complex and requires customers to install plug-ins, which is prone to incompatibility. At the same time, when the current network virus flood, many security policies on Client browsers prohibit third-party plug-ins from being installed, which makes deployment and maintenance quite difficult.
From the above technical implementation point of view, the current shortcomings of the two methods are very obvious either non-real-time, and the server load is huge; or the installation of plug-ins does not play the advantages of web. Therefore, we must jump out of the conventional method to find another method. Fortunately, after the author's research and attempts, we can basically find the implementation idea of implementing the real-time active notification client on the server.
Unveil the secrets
In advance, the author will only provide implementation principles and reference code segments in the current article, and will not provide the architecture and class design for designing this function into components. I am writing another article on the design of Ajax push components.
Back to the question, let's start with the client. Because of the stateless non-connection feature of the Web, if we want to implement the push method on the Web, we must first establish a communication connection with the server. However, we require that no plug-ins be installed. First, we should think of the XMLHTTPRequest object. This is very correct. How can we establish a connection with the server? This communication connection does not block the running of the browser's subject, so we cannot use synchronous requests. Therefore, we must use Asynchronous Communication, the exactly-expected XMLHttpRequest is an asynchronous request method that has no special restrictions on the request response, which is in line with our need to establish long-term connections with the server, microsoft may also plan to provide support for the browser push mode at some time in the future. The following is an instance segment for establishing a long-term communication connection:
VaR XMLHTTP = new activexobject ("msxml2.xmlhttp. 5.0 ");
Function connectserver ()
{
XMLHTTP. Open ("Post ","Http: // 127.0.0.1: 5565 ", true );//Create an asynchronous communication XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded; charset = UTF-8 ");
VaR M = XMLHTTP. Send ("Current viewed ID ");
}
XMLHTTP. onreadystatechange = function ()
{
If (XMLHTTP. readystate = 4)
{
// Determine whether the returned value is normal
If (XMLHTTP. Status = 200)
{
// Execute your Method
VaR S = XMLHTTP. responsetext; // get the information sent from the server
// Execute the Code related to your processing of the event
}
}
SetTimeout (connectserver (), 100); // re-establish the next connection
}
Connectserver ();
Note: 127.0.0.1 is the instance server. You can change this address when writing a program. Every time onreadystatechange is called back, another connection should be established. The client will be disconnected after each server responds to the client, therefore, after each server response, the client should establish a new connection to wait for the next notification from the server.
Now that the client can establish a persistent connection with the server, how can the server notify the client? Okay, now let's solve this problem. When an XMLHTTP request from the client is sent to the server, the server receives the request and suspends it instead of responding immediately, the client is not responded to until the server generates an event to notify the client. How can I suspend the request? There are two solutions:
1. Implement a serverlet (Java) or httphandle (.. net) to receive the request. when the request is called, we can block the call on this thread until the server generates an event to notify the client.
2. Implement a simple httpserver to receive and process responses. A thread is used to listen to a specified port. When a request arrives, the socket used for response is stored in the memory list, when the server receives an event notification, it retrieves the corresponding socket from the list and responds.
The first scheme will block the thread. because the number of threads that the Web server responds to various requests is limited, the first scheme will cause performance loss and instability. Therefore, the second solution is feasible. The reference code based on Java is as follows:
Code snippet for receiving XMLHTTP requests
Public static hashmap <string, socket> clientsockets = new hashmap <string, socket> ();
Private Boolean serverstarted = true;
.....
.....
.....
Java.net. serversocket SS;
Ss = new java.net. serversocket (5565); // set the listening port
While (serverstarted) // Loop Response
{
Try {
Java. Lang. thread. Sleep (100 );
} Catch (interruptedexception e ){
Break;
}
Java.net. Socket S = ss. Accept ();
Byte [] B = new byte [S. getinputstream (). Available ()];
S. getinputstream (). Read (B );
String requeststr = new string (B, "UTF-8 ");
// Analyze the identifier sent by the client from the request string
String clientid = parserequeststr (requeststr );
Clientsockets. Put (clientid, S );
}
........
Code snippet when a server event requires notifying the customer segment
Java.net. Socket S = clientsockets. Get (clientid); // retrieve the required client segment socket from the list
If (S = NULL)
Return;
Java. Io. printwriter P = new java. Io. printwriter (S. getoutputstream ());
P. println ("HTTP/1.1 200ok ");
P. println ("Content-Type: text/html; charset: UTF-8 ");
P. println ("Content-Length:" + MSG. Length (); // MSG indicates the information that the server wants to send to the client.
P. println ();
P. println (MSG );
P. Flush ();
S. getoutputstream (). Flush ();
S. getoutputstream (). Close ();
S. Close ();
Clientsockets. Remove (clientid); // remove the sent socket
So far, the server has proactively notified the client about the basic implementation principles and reference code segments of the Ajax push technology. I believe you can implement a better push technology based on the technical points given by the author.
Conclusion
Finally, I would like to add a few more words. The author only gives the key implementation in the article, but there are still many considerations to apply this technology in practice, here are some important points to consider:
1. Regarding the exception of the customer segment, how can I check whether the connection has been disconnected if the connection fails to be automatically reconnected with the least resource?
2. The server needs to regularly verify the sockets in the list to ensure that the connections in the list are available.
3. A large number of messages must be continuously notified to the client for queue processing.
Now let me talk about it. If you have more questions and suggestions, please contact me via email, I hope you can ask someone after reading this article, "is your application Ajax pushed today?"

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.