存储聊天应用程序的“用户在线”列表(php / ajax)

I have several chat rooms. Currently, I store the list of chat users in a php variable. If a user enters or leaves the room, the user's name is added/removed from that list. To make this storage persistent, I use memcached. To update the status of the chat room and send the user list to all users in the chat room, I use periodical ajax requests that fetch the user list into the browsers of the users who are in the chat.

It works okay. But I doubt that sending the whole list of chat users to everybody every XX seconds is a good idea if there are a couple of hundred people in the chat.

How are chat rooms usually dealing with this problem?

Have no idea how they do, but here are some ways you could. Remember to measure before and after you optimize.

  • Version the list. Don't get the full list if you have an up to date version.
  • Diff the list. Send only the updates since the last update.
  • Log this list. Cache or push updates as new events occur.

Honestly, what you are doing sounds pretty good. Keep doin what ya doin. Maybe keep track of the last list and only send an update if they have changed in the last x time? If you really want to save a few bytes.

I would push the list updates through the same channel that the chat messages go through, too. If it's an endless-loading page, maybe you could inject something like this in the page:

<script>updateUserlist({user:"alice", eventtype:"leave"});</script>

The way I run my chat rooms, I timestamp all the new messages and new sign ins and sign outs.

When a user enters a room, I download the full list. Periodically(via an AJAX with JSON call), I will download any new events (messages, logins and logouts). And update the relevant lists accordingly.

It is possible to push data from server to client (http://stackoverflow.com/questions/19995/is-there-some-way-to-push-data-from-web-server-to-browser). However, if you would still like to do polling, I would implement something similar to HTTP 304 response.

Thanks for all the suggestions. Additionally, I will look into running a comet server. The long-polling approach just would not scale well.