Sorry folks, Cool.io is retired.
Please check out Celluloid::IO instead.
Do you like Sinatra? Do you like Node.js? Wish you could write Node.js apps in Ruby as easily as you write Sinatra apps? Let's ask Cool.io how.
A Quick Tour
Hi, I'm Coolio, the fabulously wealthy lyricist and rapper behind Gangsta's Paradise. Let's write an event-driven echo server:
See? Look at that, it's easy! But how's it work? Let's take a peek into the parts of my DSL:
- cool.io.server - This creates a new server that listens on the given host and port. When someone connects to our server, the callbacks specified in the block are fired for various events.
- on_connect, on_close, on_read - These are callbacks fired when events occur, specifically when we get a new connection to our echo server, when a connection closes, and when data is read from the network.
- cool.io.run - This runs the default cool.io event loop. The event loop will block, waiting for events. In the case of our echo server, it will wait for incoming connections, and once it's received them, it will wait for the client to send data, the echo it back to the client.
Okay, now you understand the basics of writing servers. But how do we write clients? Let's write a client for our echo server:
Get it? Writing clients is a lot like writing servers. There's just a few differences:
- cool.io.connect - This tells me you want to connect to a remote server. Just give me an address, port, and a block of callbacks
- on_resolve_failed and on_connect_failed - These are callbacks fired when DNS fails to resolve or if we couldn't open a connection. on_connect_failed will always get fired if the connection fails and on_resolve_failed is a callback that lets you handle DNS resolution failures specifically.
Need to write yo' self a web app that includes Cool.io coolness? Check out how to use Cool.io in Rainbows!, an asynchronous web server:
That's all it takes to get your Cool.io code running alongside a Rack application. Aight, now write yourself some event driven code in Ruby!