Class: Sip2::NonBlockingSocket
- Inherits:
-
Socket
- Object
- Socket
- Sip2::NonBlockingSocket
- Defined in:
- lib/sip2/non_blocking_socket.rb
Overview
Sip2 Non-blocking socket From spin.atomicobject.com/2013/09/30/socket-connection-timeout-ruby/
Constant Summary collapse
- DEFAULT_TIMEOUT =
5- SEPARATOR =
"\r".freeze
Class Method Summary collapse
-
.connect(host, port, timeout = DEFAULT_TIMEOUT) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/MethodLength.
Instance Method Summary collapse
- #gets_with_timeout(separator = SEPARATOR) ⇒ Object
- #send_with_timeout(message, separator = SEPARATOR) ⇒ Object
Class Method Details
.connect(host, port, timeout = DEFAULT_TIMEOUT) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/MethodLength
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/sip2/non_blocking_socket.rb', line 26 def self.connect(host, port, timeout = DEFAULT_TIMEOUT) # Convert the passed host into structures the non-blocking calls can deal with addr = Socket.getaddrinfo(host, nil) sockaddr = Socket.pack_sockaddr_in(port, addr[0][3]) NonBlockingSocket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0).tap do |socket| socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) socket.connection_timeout = timeout begin # Initiate the socket connection in the background. If it doesn't fail # immediately it will raise an IO::WaitWritable (Errno::EINPROGRESS) # indicating the connection is in progress. socket.connect_nonblock(sockaddr) rescue IO::WaitWritable # IO.select will block until the socket is writable or the timeout # is exceeded - whichever comes first. if IO.select(nil, [socket], nil, timeout) begin # Verify there is now a good connection socket.connect_nonblock(sockaddr) rescue Errno::EISCONN # rubocop:disable Lint/HandleExceptions # Good news everybody, the socket is connected! rescue StandardError # An unexpected exception was raised - the connection is no good. socket.close raise end else # IO.select returns nil when the socket is not ready before timeout # seconds have elapsed socket.close raise ConnectionTimeout end end end end |
Instance Method Details
#gets_with_timeout(separator = SEPARATOR) ⇒ Object
19 20 21 22 23 |
# File 'lib/sip2/non_blocking_socket.rb', line 19 def gets_with_timeout(separator = SEPARATOR) ::Timeout::timeout (connection_timeout || DEFAULT_TIMEOUT), ReadTimeout do gets separator end end |
#send_with_timeout(message, separator = SEPARATOR) ⇒ Object
13 14 15 16 17 |
# File 'lib/sip2/non_blocking_socket.rb', line 13 def send_with_timeout(, separator = SEPARATOR) ::Timeout::timeout (connection_timeout || DEFAULT_TIMEOUT), WriteTimeout do send + separator, 0 end end |