Socket Programming in Ruby

March 01, 2011 · 1 min read

I was recently asked if I had the content of some articles that I posted a long time ago on a blog I used to run. After some searching I managed to scrape together the content using the Wayback Machine. It's faithfully recreated here without changes, something I should have done when I first bought the barkingiguana.com domain.

I decided today to find out how hard socket programming in Ruby would be -- mainly because I'd finished a huge chunk of work and could find nothing better to do. The alternative was tidying the kitchen, so the bar was low. A quick search turned up an extract from the Pragmatic Ruby book at [rubycentral.com](http://www.rubycentral.com/book/lib_network.html), and that simple library reference proved surprisingly handy. I'll need to buy a copy of that book. Somebody remind me when I'm feeling flush. Anyway, unsurprisingly, it's very easy. Here's how you open and work with a TCP socket. First, fire up irb and load the socket library: ``` kawaii:~ craig$ irb irb(main):001:0> require 'socket' => true ``` Then open a socket, passing in a block: ``` irb(main):002:0> TCPSocket.open('xeriom.net','smtp') do |t| irb(main):003:1* t.gets irb(main):004:1> end => "220 pluto.xeriom.net ESMTP Postfix\r\n" ``` Simple, elegant, delightful. Checking whether a socket is listening is just as easy. Since we already have the socket library loaded: ``` irb(main):005:0> begin irb(main):006:1* t = TCPSocket.new('xeriom.net',8000) irb(main):007:1> t.close irb(main):008:1> rescue irb(main):009:1> "Error: socket not open" irb(main):010:1> end => "Error: socket not open" ``` Done. Perhaps a little too easy -- now I have nothing to do except tidy. Tomorrow I'll play with opening many sockets simultaneously, checking if each one is open or closed. Bonus points if you beat me to it, or if you can make Java look as clean.
Questions or thoughts? Get in touch.