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) }
    end
end
server = SVNServer.new(18500)
server.start
server.join

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.