Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment