Created
October 30, 2009 21:09
-
-
Save mperham/222735 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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