Cool.io: Node.js-style Event Driven Awesomeness for Rubyists

By Peter Cooper

Been missing esteemed rapper and author Coolio (real name Tony Arcieri) recently? He's been busy studying Ruby and building Cool.io (or GitHub repo), a Node.js and Sinatra inspired "event framework" for Ruby powered by libev. Think EventMachine but with a cuter, Sinatra-style API. cool.io isn't exactly new, though, it's a rewrite-meets-rebrand of Rev (which started life back in 2007).

Cool.io (formerly known as Rev, and pronounced like Coolio of Gangster's Paradise fame) is an event framework for Ruby built on libev, the same library that provides high performance asynchronous I/O for Node.js. Cool.io is great for building TCP clients and servers which handle large numbers of connections and are primarily I/O bound. Cool.io also provides APIs for filesystem monitoring. Cool.io is an alternative to EventMachine, albeit one which using Ruby's own native I/O primitives rather than reinventing them, and does as much as possible in Ruby instead of C, which should make it easier for interested contributors to hack on.

Tony Arcieri

You can install cool.io with gem install cool.io (it just feels weird to have a period in a gem name, no?) and be up and running quickly with cool.io's default example script:

require ' rubygems ' require ' cool.io ' ADDR = ' 127.0.0.1 ' PORT = 4321 cool . io . server ADDR , PORT do on_connect do puts " #{remote_addr} : #{remote_port} connected " end on_close do puts " #{remote_addr} : #{remote_port} disconnected " end on_read do | data | write data end end puts " Echo server listening on #{ADDR} : #{PORT} " cool . io . run

This program listens on localhost at port 4321, accepts connections, and echos data back to them. You could make it serve up Web pages (especially through Rainbows), have it share data between clients to make a chat system or.. whatever you like.

Unlike a non-event driven single threaded daemon, a cool.io powered daemon can take multiple connections and manage them simultaneously without needing to fork or create extra threads. In this respect it's similar to EventMachine although it doesn't use EventMachine at all (but cutely has an EventMachine emulator baked in) and is developed mostly in Ruby rather than C.

Want to know more? cool.io's snazzy homepage is the place to start.