“谁在线?” 红宝石网络计划
我有几个嵌入式 Linux 系统,我想编写一个“谁在线?” Ruby 中的网络服务。 以下是我的代码的相关部分:
mySocket = UDPSocket.new
mySocket.bind("<broadcast>", 50050)
loop do
begin
text, sender = mySocket.recvfrom(1024)
puts text
if text =~ /KNOCK KNOCK/ then
begin
sock = UDPSocket.open
sock.send(r.ipaddress, 0, sender[3], 50051)
sock.close
rescue
retry
end
end
rescue Exception => inLoopEx
puts inLoopEx.message
puts inLoopEx.backtrace.inspect
retry
end
end
我从 PC 发送“KNOCK KNOCK”命令。 现在的问题是,由于它们都同时收到消息,因此它们也尝试同时响应,这会导致 Broken Pipe 异常(这就是我的“救援重试”代码的原因)。 这段代码有时工作正常,但是; 有时,代码的救援重试部分(由 sock.send 中的 Broken Pipe 异常唤醒)会导致一个或多个系统在 5 秒左右后做出响应。
既然我假设我无法逃脱 Broken Pipe 异常,是否有更好的方法来执行此操作?
I have several embedded linux systems that I want to write a 'Who's Online?' network service in Ruby. Below is related part of my code:
mySocket = UDPSocket.new
mySocket.bind("<broadcast>", 50050)
loop do
begin
text, sender = mySocket.recvfrom(1024)
puts text
if text =~ /KNOCK KNOCK/ then
begin
sock = UDPSocket.open
sock.send(r.ipaddress, 0, sender[3], 50051)
sock.close
rescue
retry
end
end
rescue Exception => inLoopEx
puts inLoopEx.message
puts inLoopEx.backtrace.inspect
retry
end
end
I send the 'KNOCK KNOCK' command from a PC. Now, the problem is since they all receive the message at the same time, they try to respond at the same time too, which causes a Broken Pipe exception (which is the reason of my 'rescue retry' code). This code works OK sometimes but; other times the rescue retry part of the code (which is waked by Broken Pipe exception from sock.send) causes one or more systems to respond after 5 seconds or so.
Is there a better way of doing this since I assume I cant escape the Broken Pipe exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现异常是由发送命令中的“r.ipaddress”部分引起的,这与我的嵌入式系统的内部结构有关......
I have found that exception was caused by the 'r.ipaddress' part in the send command, which is related to my embedded system's internals...