JavaScript, Comet, and RabbitMQ Fun
I’ve been kicking around the idea of making a sequel to HackWars, the game I created as a hobby in university. Many of the problems facing the original game were technological. Even though we had lots of coders willing to help out, it was difficult to bring people up to speed, iterating was brutal, and the whole beast was/is pretty tipsy.
My plan: Develop a game with similar play mechanics but with much more scalable and manageable architecture:
- A key/value store, such as Redis, for saving player information.
- RabbitMQ for message passing and parallelization.
- JavaScript/CSS/HTML for the view (I sure as hell won’t miss Applets).
To test my plan, I recently started mucking with using Comet in association with RabbitMQ. The results were pretty cool, I thought I’d share them.
The Client Side
Comet is a buzz word that describes web-applications that operate based on messages pushed from the server, rather than the more common, “are we there yet?”, pull-based architecture.
Orbited provides a pure JavaScript/HTML socket in the browser.
I implemented a push-based architecture using orbited. Orbited creates a connection to a server that you proceed to keep open as long as possible, you allow orbited to re-connect when necessary. Here’s the nitty-gritty:
- You create a configuration file that routes the orbited socket to the Comet server. My configuration file routes all connections made to the orbited server to a server I run on port 9000.
[access]
* -> localhost:9000 - Using the orbited JavaScript libraries, you open a socket to port 9000.
I have started building a JavaScript library for handling messages to and from the Comet server. Outbound messages simply use jQuery and $.ajax() to post to a light-weight HTTP controller. Inbound messages arrive via the persistent connection opened by Orbited.
The Server Side
There are three parts to the server-side architecture:
A CherryPy server handles inbound messages and dispatches them to RabbitMQ — potentially this might be a user chatting, clicking somewhere in the GUI, whatever:
The Comet server listens for inbound connections from Orbited on port 9000, and proceeds to spawn the connection off into its own thread:
Finally, the thread listens on RabbitMQ for messages intended for a given user. These are dispatched to the client’s browser, via the open socket.
The code is pretty rough, but I’m pretty happy with how things are working.
I can’t wait to build out this architecture more, hopefully into a fairly addictive game — at which point I can move to the Caribbean, and live on my spoils.