3

like in client sockets

     socket = Socket.new(AF_INET, SOCK_STREAM, 0) 
     sockaddr = Socket.pack_sockaddr_in(2200, 'localhost') 
     socket.connect_nonblock(sockaddr)
     server_msg = socket.recv_nonblock(3058)
                   vs
     clientSession = TCPSocket.new( "localhost",2200)
     server_msg = socket.recv(3058)

like in server

      socket = Socket.new(AF_INET, SOCK_STREAM, 0)
      sockaddr = Socket.sockaddr_in(6212, 'localhost')
      socket.bind(sockaddr)
      socket.listen(5)
                    vs
      server = TCPServer.new("localhost",3000)

Is it syntactically both different or logically we should make them non-blocking?

kanna
  • 366
  • 2
  • 19

1 Answers1

0

Maybe you could use timeouts?

We use the following code for ruby socket clients to time out if there is no response:

@socket = TCPSocket.new(host, port)

timeout=30.0
ready = IO.select([@socket], nil, nil, timeout)

if ready
  response = @socket.recv(SOCKET_READ_SIZE)
else
  message = "Socket communications timed out after #{timeout} seconds"
  logger.error message
  @socket.close if @socket.present?
  raise message
end
ianpetzer
  • 1,828
  • 1
  • 16
  • 21
  • 2
    Using Timeout.timeout is general a bad idea. Performance: Timeout.timeout works by spawning a thread (costly). Functionality: Timeout.timeout depends on the blocking call being interruptible. Fragile: it works by raising an exception in the block, which can happen at any place. For instance, it could raise just after the socket got constructed, which would lead to a leak. – kanna Dec 15 '12 at 08:54
  • 3
    As far as I understand, Using IO.select does not rely on Timeout.timeout. See http://stackoverflow.com/a/12111120/216314 for an explanation – ianpetzer Dec 20 '12 at 13:45