EventMachine is an event-driven I/O and lightweight concurrency library for Ruby. It provides event-driven I/O using the Reactor pattern, much like JBoss Netty, Apache MINA, Python’s Twisted, Node.js, libevent and libev.

PeepCode has nice screencasts for the EventMachine, and I coded some examples based on that.

The previous post was about a simple UDP server to handle user-specified jobs. I wrote similar feature using EventMachine as follows. The server accepts jobs like “SMALL” or “LARGE” which takes several seconds to complete, and then responds with a message. In the following example, standard “nc” command is used for the client part.

With EventMachine, asynchronous job handling can be simply implemented with the event-driven model. It also just works concurrently. It’s nice.

Server

% ruby server.rb
2013-07-14T00:40:00+09:00 : Received LARGE A
2013-07-14T00:40:02+09:00 : Received LARGE B
2013-07-14T00:40:03+09:00 : Received LARGE C
2013-07-14T00:40:05+09:00 : Completed in 5 second with param = A
2013-07-14T00:40:07+09:00 : Completed in 5 second with param = B
2013-07-14T00:40:08+09:00 : Completed in 5 second with param = C
2013-07-14T00:40:35+09:00 : Received LARGE D
2013-07-14T00:40:36+09:00 : Received SMALL E
2013-07-14T00:40:37+09:00 : Completed in 1 second with param = E
2013-07-14T00:40:40+09:00 : Completed in 5 second with param = D
2013-07-14T00:40:54+09:00 : Received XXX
2013-07-14T00:40:54+09:00 : Invalid command is specified

Client

% nc -u 0.0.0.0 9000
LARGE A
LARGE B
LARGE C
Completed in 5 second with param = A
Completed in 5 second with param = B
Completed in 5 second with param = C
LARGE D
SMALL E
Completed in 1 second with param = E
Completed in 5 second with param = D
XXX
Invalid command is specified