Multithreaded server in 5 lines? Damn.

Ok, last post was a rant was about how Ruby sucks. This post is about how damned cool it is. Long story short, I needed to switch some code from a fork() model to multithreaded or select(). I really wasn’t excited about working with threads or Ruby’s rather coarse select() API. Then I found GServer.

Here’s the code:

class SVNServer < GServer
    def serve(socket)
        loop { proc_client(socket) }
server =

Basically, this code listens on tcp:18500 for connections, and then handles each connection over to the function proc_client(). All proc_client() needs to do when it’s done is call close() on the socket and return. Too simple.

One thing I don’t understand is why GServer isn’t covered in O’Reilly’s Ruby Cookbook. That’s a big WTF? in my book.

0 thoughts on “Multithreaded server in 5 lines? Damn.

  1. Actually, the Ruby Cookbook (1st ed, June 2006) does have an article on GServer. It’s article 14.14: Writing an Internet Server, pp 532-4.

Leave a Reply

Your email address will not be published. Required fields are marked *