How do I set the socket timeout in Ruby?

前端 未结 3 1010
日久生厌
日久生厌 2020-12-08 11:24

How do you set the timeout for blocking operations on a Ruby socket?

3条回答
  •  伪装坚强ぢ
    2020-12-08 11:33

    I think the non blocking approach is the way to go.
    I tried the mentioned above article and could still get it to hang.
    this article non blocking networking and the jonke's approach above got me on the right path. My server was blocking on the initial connect so I needed it to be a little lower level.
    the socket rdoc can give more details into the connect_nonblock

    def self.open(host, port, timeout=10)
     addr = Socket.getaddrinfo(host, nil)
     sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)
    
     begin
      sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3]))
     rescue Errno::EINPROGRESS
      resp = IO.select([sock],nil, nil, timeout.to_i)
      if resp.nil?
        raise Errno::ECONNREFUSED
      end
      begin
        sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3]))
      rescue Errno::EISCONN
      end
     end
     sock
    end
    

    to get a good test. startup a simple socket server and then do a ctrl-z to background it

    the IO.select is expecting data to come in on the input stream within 10 seconds. this may not work if that is not the case.

    It should be a good replacement for the TCPSocket's open method.

提交回复
热议问题