Wednesday, May 29, 2013

Echo Server and Client in Ruby

The echo server and client is the Hello, World! of network programming. Below is an example implementation in Ruby, where echod.rb is the server and echo.rb is the client. By default, the server listens on 127.0.0.1, port 8756, and the client connects to that address. Both programs accept two optional positional arguments, where the first is the host and the second is the port.

echod.rb


#!/usr/bin/env ruby

require 'socket'

class EchoServer
  def initialize(host='127.0.0.1', port=8765)
    @host = host
    @port = port
    @server = TCPServer.open(host, port)
  end
  def start_message
    STDOUT.puts "The server is running on #{@host}:#{@port}"
    STDOUT.puts "Press CTL-C to terminate"
  end
  def serve_forever
    start_message
    while client = @server.accept
      line = client.gets
      client.puts line
      client.close
    end
  end
end

host = '127.0.0.1'
port = 8765

if not ARGV.length.between?(0,2)
  puts 'usage: echod [HOST [PORT]]'
  Process.exit(1)
end

case ARGV.length
when 1
  host = ARGV[0]
when 2
  host = ARGV[0]
  port = ARGV[1].to_i
end

echod = EchoServer.new(host, port)
echod.serve_forever

echo.rb


#!/usr/bin/env ruby

require 'socket'

class EchoClient
  def initialize(host, port)
    @host = host
    @port = port
  end
  def request(msg)
    s = TCPSocket.open(@host, @port)
    s.puts msg
    response = s.gets.chomp
    s.close
    response
  end
end

host = '127.0.0.1'
port = 8765

if not ARGV.length.between?(0,2)
  puts 'usage: echo [host [port]]'
  Process.exit(1)
end

case ARGV.length
when 1
  host = ARGV[0]
when 2
  host = ARGV[0]
  port = ARGV[1].to_i
end

echo = EchoClient.new(host, port)
puts 'Enter an empty line to quit'
while true
  line = STDIN.gets.chomp
  if line == ''
    break
  end
  response = echo.request(line)
  STDOUT.puts response
end

Below is an example use of the two programs.

example


$ ./echod.rb &
$ ./echo.rb
Enter an empty line to quit
hello
hello
bye
bye

$

1 comment:

  1. Thanks for the brief examples. Serves good for a starting point. But you may include comment corresponding to each step too for this to be more useful.

    ReplyDelete