一般来说,我对编程相当陌生,我在客户端和服务器端都使用EventMachine来打开它们之间的websocket连接。
我的问题在于客户端,以及当连接因网络连接问题而丢失时。
def websocket_connection
EM.run do
begin
puts "Connecting"
ws = WebSocket::EventMachine::Client.connect(:uri => "Server Info")
puts "Success WS: #{ws}"
rescue
puts "I've been rescued"
puts "Rescue WS: #{ws}"
ws = nil
sleep 10
websocket_connection
end
ws.onopen do
puts "Connected!"
end
ws.onping do
put "Ping!"
end
ws.onmessage do |msg|
puts msg
end
ws.onclose do |code|
puts "Connection Closed!"
puts "Code: #{code}"
ws = nil
sleep 10
websocket_connection
end
end
end这与服务器连接得很好,但是如果我拔出网络连接并将其插入,我将陷入一个无限循环中,试图与代码1002 (WebSocket协议错误)重新连接。
我试图在关闭时调用EM.reconnect(服务器、端口、ws),但是它崩溃并抛出“`connect_server”错误:无法解析地址:请求的名称是有效的,但没有找到所请求类型的数据。这是有道理的,因为它不能联系DNS。即使将EM.reconnect封装在一个开始救援中,它也只是尝试过一次,再也没有尝试过。
我尝试过停止EventMachine和close (EM.stop),但是它被困在了一个试图重新连接的无限循环中。
我不太确定如何让这个客户端在网络丢失后重新连接到服务器。
编辑:上面的代码更新了一点。
CMD线:
Success WS: #WebSocket::EventMachine::Client:0x00000002909ac8拉式以太网电缆
Rescue WS:连接以太网电缆
Success WS: #WebSocket::EventMachine::Client:0x000000031c42a8 Success WS: #WebSocket::EventMachine::Client:0x000000031a3d50 Success WS: #WebSocket::EventMachine::Client:0x00000003198a90CTRL +C
block in websocket_connection': undefined methodonopen‘for nil:NilClass (NoMethodError)
所以它似乎认为它的连接,我没有看到任何连接在服务器端。
发布于 2017-06-02 23:36:41
好吧,我找不到一种方法来使用EventMachine进行适当的重新连接。当您放弃网络连接时,EventMachine中似乎发生了一些奇怪的事情。最后,我在一个新的进程下重新启动了ruby应用程序,然后删除了当前的脚本,这不是最好的方法,但经过一周的尝试,重新连接工作通过EventMachine,我刚刚放弃了。此代码在下面工作。
def websocket_restart
exec "ruby script"
exit 0
end
def websocket_connection
EM.run do
begin
puts "Connecting"
ws = WebSocket::EventMachine::Client.connect(:uri => "Server Info")
rescue
websocket_restart
end
ws.onopen do
puts "Connected!"
end
ws.onping do
put "Ping!"
end
ws.onmessage do |msg|
puts msg
end
ws.onclose do |code|
puts "Connection Closed!"
puts "Code: #{code}"
websocket_restart
end
end
endhttps://stackoverflow.com/questions/44314217
复制相似问题