Short Chat Server in Clojure

After seeing a neat little demo of a chat server in node.js, I wondered exactly what it’d look like to try and do something similar in my latest linguistic fling, Clojure. I was surprised at how quickly I could code it up (all in all, about 2 hours with numerous interruptions) and how simple it actually was.

First the code, then I’ll talk about it a bit:

So in 75 lines we have a chat server with rooms, and I think the code is short, clear and compartmentalized. The first segment is only about 16 lines, but it provides a robust framework for synchronized membership and asynchronous output to other connections. Really, that was the easiest part of the whole program.

I thought maybe the node.js server would have an advantage because of it’s (very cool) integrated event-based I/O system, which has a huge advantage for this sort of thing. But I was pleasantly surprised by how powerful and well-chosen Clojure’s built-in primitives are. Agents, in particular, are a clever way to model asynchronous objects that self-update their state based on outside input. It’s a very natural way to bring some erlang-ish goodness into the imperative world.

But what’s really cool about this is that I could easily drop into Java libraries at any time. If I wanted to bring in Netty or integrate Java’s SSL libraries, it’d be a relatively simple matter, all while still within clojure.

You can see the whole project at github.