Comet is a technique to stream data, or “push” events to the web browser, instead of making the client poll the server every few seconds. This lets the client receive near real-time updates. If you want to read more about Comet, check out the article on Wikipedia, more specifically, the section about Ajax with long polling, as this is what our server will implement.
I chose web based chat because it is a great “hello world” for learning how Comet works, and I really enjoy programming chat related stuff (see my very old implementation of GameRanger)
Before we get into any code, we have to talk about how the overall chat system works. Here are a few specifications.
- Erlang is going to handle all server-side tasks.
- Mochiweb will be used to serve the browsers.
- There will be only one (global) chat room.
- When a user sends a message, all others in the room will see it.
Okay, that should do it for now. That is the very basic outline of what the chat system needs to do. Now let's talk about the server.
The server will use Erlang's OTP feature to make sure that all of our services remain running and are monitored.
We are going to have the following logical services managed by OTP:
The other modules are:
- chat_mailbox - handles mailbox processing
- chat_util - helper functions for the application
- chat_sup - supervisor
- chat_server - the chat_server application
This module will be used to maintain the state of our chat room, and allow us to implement any "chat_room" logic, such as join/leave, sending messages, etc,.
This module is very important, it will hold all the mailboxes for each user in the chat room. Whenever we want to notify a user of something, we will send a message to the "post office". The post office will then relay the message to an individual user's mailbox. After the message has arrived in a user's mailbox, the mailbox may notify our web server, and the web server can notify the client's web browser. (I know, that's a lot handle, but don't worry, it will be explained).
Finally, the chat_web module is what the web browsers will be talking to, this is the front-end of the chat system. The web module will handle the basic tasks, such as joining the chat room, sending messages, and of course, receiving messages.
In Part 2, we will implement the chat_mailbox module for our chat server. (Source code will be included).