Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the socket timeout in Ruby?

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

like image 999
readonly Avatar asked Oct 23 '08 21:10

readonly


People also ask

How do you set a socket timeout?

Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000);

What is timeout in socket?

socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.

What is socket in Ruby?

Sockets are endpoints of a bidirectional communication channel. Sockets can communicate within a process, between processes on the same machine or between different machines. There are many types of socket: TCPSocket , UDPSocket or UNIXSocket for example.


2 Answers

The solution I found which appears to work is to use Timeout::timeout:

require 'timeout'
    ...
begin 
    timeout(5) do
        message, client_address = some_socket.recvfrom(1024)
    end
rescue Timeout::Error
    puts "Timed out!"
end
like image 81
readonly Avatar answered Sep 17 '22 14:09

readonly


The timeout object is a good solution.

This is an example of asynchronous I/O (non-blocking in nature and occurs asynchronously to the flow of the application.)

IO.select(read_array
[, write_array
[, error_array
[, timeout]]] ) => array or nil

Can be used to get the same effect.

require 'socket'

strmSock1 = TCPSocket::new( "www.dn.se", 80 )
strmSock2 = TCPSocket::new( "www.svd.se", 80 )
# Block until one or more events are received
#result = select( [strmSock1, strmSock2, STDIN], nil, nil )
timeout=5

timeout=100
result = select( [strmSock1, strmSock2], nil, nil,timeout )
puts result.inspect
if result

  for inp in result[0]
    if inp == strmSock1 then
      # data avail on strmSock1
      puts "data avail on strmSock1"
    elsif inp == strmSock2 then
      # data avail on strmSock2
      puts "data avail on strmSock2"
    elsif inp == STDIN
      # data avail on STDIN
      puts "data avail on STDIN"
    end
  end
end
like image 44
Jonke Avatar answered Sep 19 '22 14:09

Jonke