Juggernaut Tutorial
This article is by Alex MacCaw. He’s a JavaScript and Ruby developer and his blog is Lead Thinking. Follow him on Twitter here: @maccman.
Juggernaut gives you a realtime connection between your servers and client browsers. This lets you do awesome things like multiplayer gaming, chat, group collaboration and more. What’s more, Juggernaut is built on top of node.js so you can take advantage of its incredible speed and scalability.
Example code is worth a thousand words, so here’s a simple group chat implementation using Juggernaut:
<script src="http://localhost:8080/application.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
jQuery(function($){
var jug = new Juggernaut;
jug.subscribe("/chats", function(data){
$("#chats").append($("<li />").text(data));
});
});
</script>
That’s it, the browser will set up a streaming connection to Juggernaut’s node server. Any messages pushed to the channel “/chats” will be sent to the client. For example, we can push data from a Ruby client:
require "juggernaut"
Juggernaut.publish("/chats", "Hello World!");
That’s all the code you need – all clients connected will see the message.
Juggernaut’s features include:
- node.js server
- Ruby client
- Supports the following protocols:
- WebSocket
- Comet
- Adobe Flash Socket
- Reconnection support
- Massive horizontal scaling
Installation
So you want to try it out? We need to install some dependencies first:
- Install node.js
- Install npm (node package manager):
curl http://npmjs.org/install.sh | sudo sh - Install socket.io:
sudo npm install socket.io - Install node-static:
sudo npm install http://github.com/cloudhead/node-static/tarball/master - Install redis-client:
sudo npm install http://github.com/technoweenie/redis-node-client/tarball/npm
Right, now we need to start Redis (install it if you don’t have it already). Juggernaut uses Redis for PUBSUB:
./redis-server redis.conf
Download Juggernaut, and start the Juggernaut server:
git clone git://github.com/maccman/juggernaut.git
cd juggernaut
node server.js
That’s it! Open http://localhost:8080 and you’ll see Juggernaut in action.
Publishing
Now we’ve got our client running, let’s publish to it. We need to install the Ruby gem to do so (don’t forget the —pre option!):
sudo gem install juggernaut --pre
And now in irb:
require "juggernaut"
Juggernaut.publish("channel1", "Yo yo yo")
You can also publish to multiple channels:
Juggernaut.publish(["channel1", "chan2"], "yo yo, my good fellow")
And send objects:
Juggernaut.publish("channel1", {:where => "is my yo yo?"})
Conclusion
So, that’s a brief introduction to Juggernaut. You can check out more use cases in the README. Now go and build something awesome!