Skip to content

Instantly share code, notes, and snippets.

@mperham
Created October 30, 2009 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mperham/222735 to your computer and use it in GitHub Desktop.
Save mperham/222735 to your computer and use it in GitHub Desktop.
# Server
require 'socket'
server = TCPServer.open(2000) # Socket to listen on port 2000
loop { # Servers run forever
client = server.accept # Wait for a client to connect
sleep 1
client.puts(Time.now.ctime) # Send the time to the client
client.close # Disconnect from the client
}
# Client
require 'socket'
hostname = 'localhost'
port = 2000
timeout = 0.7
s = TCPSocket.open(hostname, port)
secs = Integer(timeout)
usecs = Integer((timeout - secs) * 1_000_000)
optval = [secs, usecs].pack("l_2")
s.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval
s.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval
begin
a = Time.now
# read is required, as gets never times out.
while line = s.read
puts line.chop
end
rescue => ex
puts ex.message
puts "Waited #{Time.now - a} sec"
end
s.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment