Ruby TCPSocket recv 阻塞且永不返回
所以,我有以下代码:
def LSCPHandler.send_message(message, hostname, port)
s = TCPSocket.open(hostname, port)
s.print message
ret = s.recv(1024)
s.close
LSCPHandler.parse_error(ret)
return ret
end
正常情况下工作得很好。与我交谈的服务器通常会很快返回响应,并且一切都很好。
然后今天服务器出了问题。不是我的问题,但是,这导致我的整个应用程序挂起,等待接收超时。这并不完全是最佳的。
如果我没有立即收到回复,是否有办法使接收超时?我尝试查看 ruby 文档,但这真的让我很困惑(即 TCPSocket 只实现了三个方法,没有一个 open 或 receive,并且它的 Socket 的父类也没有实现这些方法。并且 Socket 的父类似乎是 Object ?我完全困惑了)
So, I have the following code:
def LSCPHandler.send_message(message, hostname, port)
s = TCPSocket.open(hostname, port)
s.print message
ret = s.recv(1024)
s.close
LSCPHandler.parse_error(ret)
return ret
end
Which works just fine, normally. The server I'm talking to returns the response pretty quickly, usually, and all is well.
Then, today, something went wrong with the server. Not my problem, BUT, this resulted in my entire application hanging, waiting for recv to time out. This isn't exactly optimal.
Is there a way to time out recv if I dont' hear something back immediately? I tried looking at the ruby documentation, but it really confuses me(i.e. TCPSocket only implements three methods, none of them open or recv, and it's parent class of Socket doesn't implemente these methods either. And Socket's parent class appears to be Object? I'm throughly confused)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将套接字上的接收超时套接字选项设置为默认值以外的其他值。棘手的一点是选择一个在所有用例中仍然有效的合适数字,即您不希望您的
recv
调用过早超时。You can set the receive timeout socket options on the socket to something else than the default. The tricky bit is to pick a suitable number that still works in all use cases, i.e. you don't want your
recv
call to timeout too early.