Building an Erlang chat server with Comet - Part 1

Introduction

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)

Chat Architecture

Before we get into any code, we have to talk about how the overall chat system works. Here are a few specifications.

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.

Server Overview

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_room

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,.

chat_postoffice

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).

chat_web

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.

Implementing chat_mailbox

In Part 2, we will implement the chat_mailbox module for our chat server. (Source code will be included).


comments powered by Disqus