Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Create a daemon / server in 11 lines of Ruby

By Peter Cooper / June 8, 2006

Lately I've been finding little known Ruby gems and trying them out. My latest find is EventMachine. EventMachine describes itself:

Ruby/EventMachine is a fast, simple event-processing library for Ruby programs. It lets you write network clients and servers without handling sockets- all you do is send and receive data. Single-threaded socket engine- scalable and FAST!

Simply install with gem install eventmachine and you can create a fast, multi-user server / daemon like so:

require 'rubygems'
require 'eventmachine'

module EchoServer
  def receive_data(data)
    send_data ">>> You sent: #{data}"
    close_connection if data =~ /quit|exit/i

EventMachine::run {
  EventMachine::start_server "", 8081, EchoServer

Once you run this, you can telnet to localhost on port 8081 and have a conversation with yourself!

You create servers using your own protocols as modules, and pass the modules to EventMachine to handle (a bit like servlets with WEBrick, but TCP rather than HTTP based). You could reasonably easily write a basic chat server (with dRb), POP3 server, or any sort of low level server you want, and EventMachine handles the whole connection and daemon side for you.


  1. Doug @ Straw Dogs says:

    Definately a gem I'll be looking into. I often forget quite how many useful ones are out there yet to be discovered. One I recently found useful for work is Adwords4r which is a Ruby API implementation of the Adwords SOAP service.

    I'll be giving this a go though.

Other Posts to Enjoy

Twitter Mentions