Simple Socket Ruby

Quick, you need to test some socket code. You need to start a server, it needs to accept a connection (just one), then the resulting socket needs to read lines of data, do some some processing (what processing you want to do is going to change all the time), and send back the result. Use any language you want, I choose Ruby. Here’s the code for an echo server:

#!/usr/bin/env ruby
require 'simple_socket'
socket_serve {|s|s}

Yes, I’m cheating. Let’s see that Simple Socket library:

##
# simple_socket.rb
# by William Taysom
# Nov. 7, 2005
# License: Use these powers only for awesome.
require 'socket'
$default_host = 'localhost'
$default_port = 6200
def with_socket host = $default_host, port = $default_port
  if not port and host.kind_of? Numeric
    port = host
    host = $default_host
  end
  if host == :serve
    server = TCPServer.new port
    t = server.accept
    server.close
  else
    t = TCPSocket.new host, port
  end
  yield t
  t.close
end<br/>
def socket_connect host = $default_host, port = $default_port
  with_socket host, port do |t|
    t.each do |line|
      t.puts yield(line)
    end
  end
end<br/>
def socket_serve port = $default_port
  with_socket :serve, port do |t|
    t.each do |line|
      t.puts yield(line)
    end
  end
end

Now we want a timer that checks how long it takes to send ten thousand short messages across a channel. No problem:

#!/usr/bin/env ruby
require 'simple_socket'
with_socket do |t|
  t.puts 'hello world'
  @time1 = Time.now
  @i = 0
  t.each do |s|
    t.puts s
    unless (@i += 1) < 10000
      @time2 = Time.now
      puts @time2 - @time1
      @time1 = @time2
      @i = 0
    end
  end
end

And that friends, is why Ruby rocks. It’s not that its more powerful or more elegant than other languages (don’t be fooled, the semantics is a mess), the thing that makes Ruby superior is its excellent libraries.