Ruby套接字编程中的标准套接字超时(秒)是多少?
我正在编写一个Ruby客户端,它将打开tcp套接字并传输数据 如果我不能在20秒内打开套接字,我将触发超时错误Ruby套接字编程中的标准套接字超时(秒)是多少?,ruby,sockets,tcp,stream,timeout,Ruby,Sockets,Tcp,Stream,Timeout,我正在编写一个Ruby客户端,它将打开tcp套接字并传输数据 如果我不能在20秒内打开套接字,我将触发超时错误 begin Timeout::timeout(20) { socket = open_socket(host, port) } rescue Errno::ECONNREFUSED puts "Failed to connect to server" rescue Timeout::Error puts "Timeout error occurred while conne
begin
Timeout::timeout(20) { socket = open_socket(host, port) }
rescue Errno::ECONNREFUSED
puts "Failed to connect to server"
rescue Timeout::Error
puts "Timeout error occurred while connecting to the server"
end
我的open_socket方法如下所示
def open_socket(host,port)
TCPSocket.new(host,port)
end
代码运行良好。我的问题是
我发现两篇文章似乎确认超时为20秒:
- 在
- In(非特定于ruby)
对于你的第二个问题,我没有答案。你就是这样做的。超时的默认值是10秒 超时(秒){…} 执行块,如果块执行在超时时间之前成功终止,则返回true, 否则,将立即终止块的执行并引发TimeoutError异常
require 'timeout'
status = timeout(5) {
# something that may take time
}
在Linux上,可以使用setsockopt/getsocktopt访问发送/接收超时
执行man 7插座并查找SO_RCVTIMEO和SO_sndtTimeo选项。setsockopt/getsockopt在Ruby中的套接字对象上可用。这是特定于Ruby实现的(我非常确定它可能无法在Jruby/rubinius上工作)。此外,使用Timeout.Timeout通常是个坏主意。性能:Timeout.Timeout通过生成线程来工作(代价高昂)。功能:Timeout.Timeout取决于阻塞调用是否可中断。易碎:它通过在块中引发异常来工作,异常可能发生在任何地方。例如,它可能在构造套接字之后立即引发,这将导致泄漏(只有当GC启动时,套接字才会关闭)