How do I set the socket timeout in Ruby?

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

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

3条回答
  •  我在风中等你
    2020-12-08 11:52

    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
    

提交回复
热议问题