Background
"Long polling" is the name used to describe a technique which:- An AJAX request is made (utilizing a javascript framework such as jQuery)
- The server waits for the data requested to be available, loops, and sleeps (your server-side PHP script)
- This loop repeats after data is returned to the client and processed (usually in your AJAX request's onComplete callback function)
There are a variety of use cases in which this technique can be handy. At the top of the list are real-time web-based chat applications. Each client executes a long polling loop for chat and user events (sign on/sign off/new message). Meebo is perhaps the greatest example of this.
It's important to note some of the server side technical limitations of long polling. Because connections remain open for considerably longer time than a typical HTTP request/response cycle you want your web server to be able to handle a large number of simultaneous connections. Apache isn't the best candidate for this type of situation. nginx and lighttpd are two lightweight web servers built from the ground up to handle a high volume of simultaneous connections. Both support the FastCGI interface and as such can be configured to support PHP. Again, Meebo uses lighttpd.
For similar reasons - it's also a good idea to choose a different sub-domain to handle long polling traffic. Because of client side browser limitations you don't want long polling connections interfering with regular HTTP traffic delivering page and media resources for your application.
Implementation
jQuery makes implementation a breeze.
01
02
03
04
05
06
07
08
09
10
11
| var lpOnComplete = function (response) { alert(response); // do more processing lpStart(); }; var lpStart = function () { $.post( '/path/to/script' , {}, lpOnComplete, 'json' ); }; $(document).ready(lpStart); |
On the server side - just like we discussed earlier:
01
02
03
04
05
06
07
08
09
10
11
12
13
| $time = time(); while ((time() - $time ) < 30) { // query memcache, database, etc. for new data $data = $datasource ->getLatest(); // if we have new data return it if (! empty ( $data )) { echo json_encode( $data ); break ; } usleep(25000); } |
That pretty much sums it up! Not that difficult, right?
As always, questions/comments are welcome, hope this helps!
No related posts.
2 comments:
Good overview, Lee. Using a tool such as can be helpful in assessment and identifying areas of need.
Website Development company
You will discover some fascinating points in time in this post but I don’t know if I see all of them interior to heart. I am learning great extra challenging on distinct blogs everyday. Lots of people will be benefited from your writing. Cheers!
Press Release Writers
Press Release Writing Service
Post a Comment