Search code examples
phpchatxajax

How can I write a real time chat using XAJAX and PHP?


How can I write a real time chat using XAJAX and PHP?

In other words, is there a way to send xajax responses from the server to multiple clients? Or is the only possibility to check for new messages every few seconds on client side?


Solution

  • No. Clients must "poll" the server repeatadly.

    I think the key here is to think interaction design. The trick is to fool the user into thinking that the chat is instant, but when in reality it updates once every 1 or 2 or 3 or 10 seconds.

    Ideas:

    1) When the user sends a message, show it directly in the chat and trigger a poll.

    2) If a poll comes back with multiple messages from other users, don't add them all at once, actually add them over a period of 1-2 sec or so, with random spacing, making it look like they're coming in "instantly" and independently. (If a bunch of messages come in at once the user is very quick to realize that the chat updated there and then, and not continiously.)

    3) If the user is idle for x amount of time. Drop the poll rate to once every 10sec or so.

    4) If the user is active, ie sending a lot of messages, poll more often.

    5) Have a static file for every channel that your write the time the chat last updated to. For instance file chat-teenfun-lastupdate.txt has the contents 1224934239 or whatever time format you prefer. Serve this file statically and let clients poll this file in order to check if the channel has updated, rather that calling chat-poll.php?ch=teenfun that does a dynamic check. Static files are served around 10-100 times faster, depending on the work involved for the dynamic script, and you're gonna need it when you get 250+ users polling.

    Good luck and have fun!

    /0

    PS. Alternatively you could actually let clients do an ajax call to the server and keep them 'hanging'. That is you accept their request and pretend to start sending data back, but then you just pause. When something happends you finish the response with the approriate data. For this to work I believe you'd need to write your own HTTP-server though, that does this specifically, as you can't have 250 php processes hanging around in memory. Maybe Lighttpd could be used in this way somehow with that LUA cache mod. I don't know. Would be interesting though. Hell I gotta try it sometime :)