EventMachine reconnection issues

Viewed 318

I am fairly new to programming in general and I am using EventMachine on both the client and server side to open a websocket connection between them.

My issue is with the Client side, and when the connection is lost due to network connectivity issues.

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

This connects to the server just fine, but if I pull the network connection and plug it back in I am stuck in an infinite loop of it trying to reconnect with code 1002 (WebSocket protocol error.).

I have tried to call EM.reconnect(server, port, ws) on close, but it crashes and throws this error `connect_server': unable to resolve address: The requested name is valid, but no data of the requested type was found. Which makes sense because it can't contact DNS. Even if wrap the EM.reconnect in a begin rescue it just tries once and never tries again.

I have tried stopping EventMachine and close (EM.stop) but that gets stuck in an infinite loop trying to reconnect.

I am not really sure how to get this client to reconnect to the server after a network lose.

EDIT: Updated the code above a little bit.

CMD Line:
Success WS: #WebSocket::EventMachine::Client:0x00000002909ac8
Pulled Ethernet Cable
Rescue WS:
Connected Ethernet Cable
Success WS: #WebSocket::EventMachine::Client:0x000000031c42a8
Success WS: #WebSocket::EventMachine::Client:0x000000031a3d50
Success WS: #WebSocket::EventMachine::Client:0x00000003198a90
CTRL + C
block in websocket_connection': undefined methodonopen' for nil:NilClass (NoMethodError)

So it looks like it thinks its connecting, I don't see any connections on the server side.

1 Answers
Related