views:

58

answers:

1

I'm planning a chat-like web application, where whenever one user posts something, all other users (that is, people with their browser pointing to that site) would get instant updates. The common choice for this is comet-style messaging using long-polling AJAX requests. Writing the client-side part with jQuery isn't much of a problem.

But I wonder how to best implement the server-side part in PHP. The posts/messages will be stored in MySQL and the question is: After writing a new post to the database, how do I notify all waiting requests, that data is available for them without using polling? Polling would work, but it's ugly and wasting resources, thus, this is what I do not want:

while (timeout not reached) {
    if ($database->has_changes())
        break;
    sleep(1);
}
handle_changes_if_any();

Is there some kind of MySQL feature that would help me here? Would some kind of IPC help? The server runs Apache.

A: 

You already mentioned one possible solution, which is to use AJAX polling to query a script periodically for updates. Polling would be done on the client side, and has nothing to do with the server side.

Another option would be to use a comet server such as Meteor. With this approach, your PHP script can notify the comet server of the new messages and the connected clients will receive the updates. Then it's just up to you to write the JavaScript to display the update to the user.

Ryan Chouinard
Traditional AJAX polling on the client-side is out of question anyway. I really do mean comet-style polling.I will have a look at Meteor, it sounds interesting.
jlh
Keep in mind terminology: AJAX is polling/pull, COMET is push. :-)
Ryan Chouinard
Isn't Comet a type of AJAX? After all, I'm still using jQuery's $.ajax() call to do it.Anyway, meteor seems to be very precisely what I've been looking for. It's just a bit cumbersome because it's a separate daemon that needs to run on the server, and there's an alternative port involved, but hopefully that will be ok.Thanks a lot!
jlh
No, they are not the same. Most COMET implementations provide a JavaScript library to connect the client to the backend daemon. These libraries maintain a constant connection on browsers that support it, but mimick it with short polling on others. When they recieve an update, they trigger an event or call a callback with the new data. Usually :-).
Ryan Chouinard