Ruby TCPSocket recv 阻塞且永不返回

发布于 2024-08-20 05:29:52 字数 497 浏览 4 评论 0原文

所以,我有以下代码:

  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

救星 2024-08-27 05:29:52

您可以将套接字上的接收超时套接字选项设置为默认值以外的其他值。棘手的一点是选择一个在所有用例中仍然有效的合适数字,即您不希望您的 recv 调用过早超时。

s.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, <timeout>)

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.

s.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, <timeout>)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文