I went ahead and spent some time this weekend messing around with WebSockets and decided to code up a simple chat room as a little educational exercise. The chat room is super simple, lacking many things you would hope to see in a real chat room, but it works as a basic demo for WebSockets. You can give it a try here:
Basic WebSocket ChatI also took this as an opportunity to learn a little more about Ruby and went ahead and coded up the server part of this in it, using the eventmachine-websocket gem to get things running quickly and easily. The server is not anything too complicated, keeping track of active connections as well as the last 128 messages sent to the server. When a client connects the server sends the client all of the messages it has stored up and then adds the client to the list of clients to broadcast future messages to. The entire thing takes up less than 30 lines of code.
On the client side, the script simply asks for a username before connecting you to the server and registering some event handlers. When a new message is received it writes some html to the messages page element and then updates its scrollbar appropriately. Most everything else on the client side is just dressing to format things the way I want.
You can grab all of the files associated with this project here.
As I note on the chat page - I am putting this up and keeping the server running as a simple demo of WebSockets. Hopefully someone finds it interesting or useful. I am not interested in moderating this, so if you use it please play nice or I will just end up shutting it down. Regardless, I do plan to continue doing some work on this to make the chat a little more fully featured - adding support for chat moderation, text formatting options, pagination and whatever else pops in my head.