A while back I posted a demo of a simple WebSocket based chat. A kind of "Hello World" program if you will. Pretty cool how simple it is to get something like that running these days if you ask me. Of course, it does have one glaring problem - it requires WebSocket support. WebSockets are pretty cool but not every browser supports them yet and so of course that means you can't rely on them if you are going to be serious about developing some sort of webapp that needs to communicate with a server.

Fortunately there are many alternatives out there to be explored. You could use Flash sockets to implement the WebSocket interface, for example. For myself I decided to convert the chat program to use the socket.io library - a process that was pleasantly simple to complete. I was even more pleased when I found that it all just worked on my very first attempt in all four browsers I tested (Chrome, Firefox, Safari & IE9). Of course, then reality hit when I tried to make it live and it stopped working in IE9 - the socket.io website says the library supports cross-domain communication (important since I have the server running on my VPS) but I ended up needing to provide it with a reduced set of transport options for it to work in IE9.

In order to use socket.io I also ending up converting the server side to javascript and running it using nodejs. I'll go ahead and walk through the process of installing all of this; there are plenty of guides out there for doing this (and really it is dead simple) but at the very least it will serve as convenient reference for myself in the future.

First up, installing nodejs is as simple as:

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install
You may need to install some dependencies first, depending on your development environment. That is all there is to it.

Next, installing npm (Node Package Manager):

curl http://npmjs.org/install.sh | sh
Of course, you will more than likely get some permission issues if you do this; for myself I have chowned my /usr/local so it isn't an issue - but I know there are many out there who frown on that. If you want to have a go at doing it without chowning /usr/local you can follow this guide. I haven't actually tried it myself though. You could also sudo it - but then you'll run into issues with installing packages and end up needing to use sudo there as well, which is not something I would feel comfortable with.

At this point installing the socket.io library is as simple as running npm install socket.io.

Anyway, I won't really go over the the code for server/client since they are really more or less just straightforward reimplementations of the previous code in javascript and using socket.io rather than the WebSocket API. You can check out the new Chat demo here. Well, not really new I guess - but it should work in many more browsers now. The source files can be downloaded here.