views:

43

answers:

1

I'm building a simple live chat into a web application running on Django, but one thing I'm confused about is how I should store the messages between users.

The chat will support multiple users, and a chat "session" is composed of users connected to one user that is the "host." The application is a sort of online document collaboration thing, so user X has a document, and users Y and Z would connect to user X to talk about the document, and that would be one chat session.

If user Y disconnected for five minutes, and then signed back in and reconnected to user X, he should not get any of the messages shared between users X and Z while he was away.

if users X, Y, and Z can have a chat session about user X's document, then users X and Y can connect to a simultaneous, but separate discussion about user Z's document.

How should I handle this? Should I keep each message in the database? Each message would have an owner user and a target user (the host), and a separate table would be used to connect users with messages (which messages are visible to what users).

Or should I store each session as an HTML file on the server, which messages get appended to?

The problem is, I can't just send messages directly between clients. They have to be sent to the server in a POST request, and then each client has to periodically check for the messages in a GET request. Except I can't just have each message cleared after a client fetches it, because there could be multiple clients. How should I set this up? Any suggestions?

+2  A: 

Give each message a timestamp (or just an incrementing ID). Then when the client pools, you send him all the messages that belong to the current chat, that happened in the last 10 seconds, along with their timestamps. The client can then filter out messages he's already got. It pools every 5 seconds or so. If you don't need the messages for logging etc, you can delete messages older than 10 seconds.

Note that if you want to implement a chat that would really feel fast and responsive, you should consider using Reverse Ajax. In that case, the answer would be different. The server should have a list of clients registered to each chat (clients that have an HttpRequest pending). The server then sends each of them every message that is posted.

And don't forget to search before you reinvent the wheel. One of django's best features is its pluggable apps archtecture.

Ofri Raviv
You can't imagine my surprise when I clicked your "Search before you reinvent the wheel" link and google was stuck to the right side of my screen.
Carson Myers