mperham (owner)

Revisions

gist: 222735 Download_button fork
public
Public Clone URL: git://gist.github.com/222735.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 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