Guest User

Untitled

a guest
Apr 21st, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. # Server
  2. require 'socket'
  3.  
  4. server = TCPServer.open(2000) # Socket to listen on port 2000
  5. loop { # Servers run forever
  6. client = server.accept # Wait for a client to connect
  7. sleep 1
  8. client.puts(Time.now.ctime) # Send the time to the client
  9. client.close # Disconnect from the client
  10. }
  11.  
  12.  
  13. # Client
  14. require 'socket'
  15.  
  16. hostname = 'localhost'
  17. port = 2000
  18. timeout = 0.7
  19.  
  20. s = TCPSocket.open(hostname, port)
  21. secs = Integer(timeout)
  22. usecs = Integer((timeout - secs) * 1_000_000)
  23. optval = [secs, usecs].pack("l_2")
  24. s.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval
  25. s.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval
  26.  
  27. begin
  28. a = Time.now
  29. # read is required, as gets never times out.
  30. while line = s.read
  31. puts line.chop
  32. end
  33. rescue => ex
  34. puts ex.message
  35. puts "Waited #{Time.now - a} sec"
  36. end
  37. s.close
Add Comment
Please, Sign In to add comment