Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top