Ruby sample scripts - sockets (examples from Ruby manual)

clnt.rb

# socket example - client side
# usage: ruby clnt.rb [host] port

require "socket"

if ARGV.length >= 2
  host = ARGV.shift
else
  host = "localhost"
end
print("Trying ", host, " ...")
STDOUT.flush
s = TCPSocket.open(host, ARGV.shift)
print(" done\n")
print("addr: ", s.addr.join(":"), "\n")
print("peer: ", s.peeraddr.join(":"), "\n")
while line = gets()
  s.write(line)
  print(s.readline)
end
s.close

svr.rb
# socket example - server side
# usage: ruby svr.rb

# this server might be blocked by an ill-behaved client.
# see tsvr.rb which is safe from client blocking.

require "socket"

gs = TCPserver.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))
socks = [gs]

loop do
  nsock = select(socks);
  next if nsock == nil
  for s in nsock[0]
    if s == gs
      ns = s.accept
      socks.push(ns)
      print(s, " is accepted\n")
    else
      if s.eof?
	print(s, " is gone\n")
	s.close
	socks.delete(s)
      # single thread gets may block whole service
      elsif str = s.gets   
	  s.write(str)
      end
    end
  end
end

tsvr.rb
# socket example - server side using thread
# usage: ruby tsvr.rb

require "socket"

gs = TCPserver.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))

loop do
  Thread.start(gs.accept) do |s|
    print(s, " is accepted\n")
    while line = s.gets
      s.write(line)
    end
    print(s, " is gone\n")
    s.close
  end
end

clnt.rb
# socket example - client side
# usage: ruby clnt.rb [host] port

require "socket"

if ARGV.length >= 2
  host = ARGV.shift
else
  host = "localhost"
end
print("Trying ", host, " ...")
STDOUT.flush
s = TCPSocket.open(host, ARGV.shift)
print(" done\n")
print("addr: ", s.addr.join(":"), "\n")
print("peer: ", s.peeraddr.join(":"), "\n")
while line = gets()
  s.write(line)
  print(s.readline)
end
s.close

svr.rb
# socket example - server side
# usage: ruby svr.rb

# this server might be blocked by an ill-behaved client.
# see tsvr.rb which is safe from client blocking.

require "socket"

gs = TCPserver.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))
socks = [gs]

loop do
  nsock = select(socks);
  next if nsock == nil
  for s in nsock[0]
    if s == gs
      ns = s.accept
      socks.push(ns)
      print(s, " is accepted\n")
    else
      if s.eof?
	print(s, " is gone\n")
	s.close
	socks.delete(s)
      # single thread gets may block whole service
      elsif str = s.gets   
	  s.write(str)
      end
    end
  end
end

tsvr.rb
# socket example - server side using thread
# usage: ruby tsvr.rb

require "socket"

gs = TCPserver.open(0)
addr = gs.addr
addr.shift
printf("server is on %s\n", addr.join(":"))

loop do
  Thread.start(gs.accept) do |s|
    print(s, " is accepted\n")
    while line = s.gets
      s.write(line)
    end
    print(s, " is gone\n")
    s.close
  end
end

Tags: