Comet Programming: Using Ajax to Simulate Server Push | 3 | WebReference

Comet Programming: Using Ajax to Simulate Server Push | 3


[prev]

Comet Programming: Using Ajax to Simulate Server Push [con't]

The PHP Server-side Code

The longPolling.php script will modify the CD inventory count in a file called CdCount.txt. Before running the Web page against a server, make sure that you've created this file in the same folder as the PHP script. It should contain the starting inventory number, such as 100. To access this file in the longPolling.php script, create the following global variable:

At the bottom of the file, include the following code to determine which action to take:

The num query string parameter is populated when the btnSubmit button is clicked, causing the updateStock() function to be called with the quantity ($num). The parameter is cast to an int so that the updateStock() function can use it in the calculation that determines the current inventory. The long poll server calls don't supply any parameters, so the $_GET['$num'] super global will be empty. That causes the getCdCount() function to execute. Since it's the simpler of the two functions, let's take a look at it first.

For those of you who don't want to enter data manually to see updates, there is some behavior built-in to the php script to simulate what purchases from multiple shoppers might look like. The srand() function seeds the random number generator before calling the rand() function. It generates a random number between 1 to 3 representing an order for CDs. A second call to rand() sets the number of seconds to wait before sending a response. Without this code, we'd either have to wait for someone (you) to submit an order, or the polling would occur as fast as a round trip from the client to the server and back takes - not a very "long" polling at all! After the function wakes up from its nap, it calls the updateStock() function with the fictitious new order:

Which brings us to the updateStock() function. It reads the number from the CDCount.txt file and subtracts the $num parameter from it to determine the new inventory count. Some basic checking makes sure that the $count never goes below zero. The new total is then written to the file and the updated $count is returned to the client:

Here's all the files that we've worked on today.


Taking the Long Polling.html Page for a Test Run

I used the Abyss Web Server for testing, but you can use any server that supports PHP. In fact, as long as you know what the script is doing, there is no reason that you can't rewrite it in the language of your choice. After all, one of the draws of long polling is that it works in any environment.

To view our long polling demo, launch your server and enter the URL to the Long Polling.html page in the address bar; it's "https://localhost/caching/Long Polling.html". You should see the number of CDs gradually decrement in steps of 1 to 3 as imaginary shoppers snatch them up. Entering a number in the Quantity textbox and clicking the Purchase button will be displayed in the next update, which may take a few seconds because of the delay that occurs in the getCdCount() function. For extra credit, feel free to write a PHP function to retrieve the CD count without the delay and use it to increment your own purchases and set the initial value in the HTML page.


I hope that you enjoyed our look at Comet and the Ajax long polling technique. It's a great way to make your pages more dynamic and to create more interactive Web apps. In a future article, we'll explore script tag long polling.


Rob Gravelle combined his love of programming and music to become a software guru and accomplished guitar player. He created systems that are used by Canada Border Services, CSIS and other Intelligence-related organizations. As a software consultant, Rob has developed Web applications for many businesses and recently created a MooTools version of PHPFreechat for ViziMetrics. Musically, Rob recently embarked on a solo music career, after playing with Ivory Knight since 2000. That band was rated as one Canada's top bands by Brave Words magazine (issue #92) and released two CDs. Rob's latest, entitled KNIGHTFALL, was a collaboration between himself, the former Ivory Knight vocalist, and legendary guitarist/producer, Jeff Waters of Annihilator fame. Rob is available for short-term software projects and recording session work. to inquire, but note that, due to the volume of emails received, he cannot respond to every email. Potential jobs and praise receive highest priority!

Original: March 6, 2009


[prev]