Flex + PHP reverse push (long polling)

Source: Internet
Author: User
Tags javascript settimeout

The reverse push technology is very popular now, and long polling is one of the key technologies for implementing reverse push.

// If you want to publish this article, please indicate the exit, no outgoing copyright notice, I do not like to see this kind of website. My work website does not indicate the person who is serving Seven {See7di # Gmail.com}
There is no doubt about the success of the HTTP protocol. It is the basis for most information exchange on the Internet. However, it also has some limitations. In particular, it is a stateless, one-way protocol. Request sent
On the Web server, the server processes the request and returns a response concurrently-that's all. The request must be sent by the client, while the server can only send data in the response to the request. This will at least affect many types
The practicality of Web applications. A typical example is a chat program. There are also some examples, such as the score or email program of the competition.

These limitations of HTTP are also the reason for its success. The request/response cycle makes it a classic model, that is, each connection uses a thread. This method can be used to quickly provide services for requests.
It has huge scalability. A large number of requests can be processed every second, and a large number of users can be processed with only a small number of servers. For many classic
Web applications, such as content management systems, search applications, and e-commerce sites, are very suitable. In any of the above
In Web applications, the server provides the data requested by the user, closes the connection, and releases the thread so that it can serve other requests. If there is still interaction after the initial data is provided, connect
The thread cannot be released, and the server cannot serve many users.

However, what if I want to maintain interaction with users after responding to the request and sending the initial data? This is often used in the early days of Web
Meta Refresh implementation. This will automatically instruct the browser to re-load the page after a specified number of seconds, so as to support simple round robin (polling ). This is not only a bad user experience, but also usually inefficient
Always low. What if no new data is displayed on the page? At this time, you have to re-render the same page. What if there are few changes to the page and most of the pages do not change? Similarly, whether necessary or not,
You have to request and retrieve everything on the page.

Ajax
The invention and prevalence of has changed the above situation. Now, the server can communicate asynchronously, so you do not have to request the whole page again. You can perform incremental updates. You only need to use XMLHttpRequest
Round-Robin server. This technology is usually called Comet. This technology has some variants, each of which has different performance and scalability. Let's take a look at these different types of Comet.

Comet Style

The emergence of Ajax makes Comet possible. The unidirectional nature of HTTP can be effectively avoided. There are actually some different ways to bypass this. As you may have guessed
The easiest way for Comet is poll ). Use XMLHttpRequest to send a call to the server. Wait for a fixed period of time (usually
JavaScript setTimeout function), and then call it again. This is a very common technology. For example, most webmail
Applications use this technology to display emails when an email arrives.

This technology has advantages and disadvantages. In this case, you expect a quick response, just like any other
Ajax requests are the same. There must be a pause between requests. Otherwise, continuous requests will throw the server, and in this case it is obviously not scalable. This pause causes a latency for the application.
The longer the pause time, the more time it takes for new data on the server to arrive at the client. If the pause time is shortened, the server may be overwhelmed again. On the other hand, this is obviously the simplest practice.
The current Comet method.

It should be pointed out that many people think that polling does not belong to Comet. On the contrary, they believe that Comet is a solution to the limitations of round-robin. The most common "true" Comet
Technology is a variant of polling, longpolling ). The main difference between polling and long polling is how long the server takes to respond. Long polling usually keeps the connection for a long time.
Time-usually several seconds, but it may be one minute or longer. When an event occurs on the server, the response is sent and immediately closed, and the polling starts again immediately.

The advantage of long polling over general polling is that once data is available, it is immediately sent from the server to the client. The request may wait for a long time, during which no data is returned, but once new data is generated, it
Will be sent to the client immediately. Therefore, there is no latency. If you have used a Web-based chat program or any program that claims to be "real-time", it is likely to use this technology.

The following is an example of how to implement regular polling in Flex and PHP.

The PHP code is simple. 

<? Php
// Timeout in seconds
$ Timeout = 60;

// Log start time
$ Start_time = time ();

// Get messge from local file
Function get_msg (){
Return file_get_contents('msg.txt ');
}

// Get message
$ Last_msg = get_msg ();

// Start the loop
While (true ){
// Get current time
$ Current_time = time ();

// Check if we are timed out
If ($ current_time-$ start_time> $ timeout ){
Echo 'timeout! No new message! ';
Break;
}

// Get latest message
$ Current_msg = get_msg ();

// Check if the message has been changed
If ($ last_msg! = $ Current_msg ){
Echo $ current_msg;
Break;
}
// Sleep 1 sec
Sleep (1 );
}

After analyzing the above Code, the principle is to execute a loop in php and access the data on the server each time,
It can be a database or a text file. Here we use a text file to determine whether the content of the text file has been updated. If yes, the data is returned to the client. in the loop, we put
The sleep (1) function suspends the code for one second each time it loops, so as not to overconsume the server's CPU resources.

The following is the flex code.

<? Xml version = "1.0" encoding = "UTF-8"?>
<! [CDATA [
// Request object
Private var req: URLRequest;

// Loader object
Private var loader: URLLoader;

// Timer
Private var timer: Timer;

[Bindable]
Private var count: Number = 0;

// Do some initializing
Private function init (): void {
Req = new URLRequest ('HTTP: // 127.0.0.1: 8080/long_polling.php ');
Loader = new URLLoader ();

Loader. addEventListener (HTTPStatusEvent. HTTP_STATUS, onStatusChange );
Loader. addEventListener (Event. COMPLETE, onComplete );
Loader. addEventListener (IOErrorEvent. IO_ERROR, onIOError );

Timer = new Timer (1000 );
Timer. addEventListener (TimerEvent. TIMER, onTimer, false, 0, true );

}

// Update the second count
Private function onTimer (event: TimerEvent): void {
Count ++;
}

// Start the request
Private function startRequest (): void {
Count = 0;
Loader. load (req );
Timer. start ();
This.txt Logs. text + = 'request started! \ N ';
}

// Status changed
Private function onStatusChange (event: HTTPStatusEvent): void {
This.txt Logs. text + = 'status changed to '+ String (event. Status) +' \ n ';
}

// Result returned
Private function onComplete (event: Event): void {
This.txt Logs. text + = 'completed! Result is '+ String (event. currentTarget. data) +' \ n ';
This.txt Logs. text + = 'start another request! \ N ';
This. startRequest ();
}

// Error handler
Private function onIOError (event: IOErrorEvent): void {
This.txt Logs. text + = 'IO Error: '+ String (event) +' \ n ';
This. stopRequest ();
}

// Stop the request
Private function stopRequest (): void {
Count = 0;
This.txt Logs. text + = 'request stopped! \ N ';
This.txt Logs. text + = '<>>>>>>>>> >>>>>>>>>> \ N'
This. timer. stop ();
This. loader. close ();

}
]>

Create a new flex project and place four spaces and two buttons on the interface. One is the start request, the other is the end request, and the other is the label to display the time spent in the current request, put another TextArea to display the log.

The request principle is also simple, implemented through URLLoader and URLRequest,
It is no different from a common http request. However, when a request gets the result (go to The onComplete () function ),
We need to re-start another query. In this way, we can simulate a network connection similar to the C/S architecture, any updates on the server will be automatically pushed to the client.

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.