Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faye WebSocket, reconnect to socket after close handler gets triggered

I have a super simple script that has pretty much what's on the Faye WebSocket GitHub page for handling closed connections:

 ws = Faye::WebSocket::Client.new(url, nil, :headers => headers)

  ws.on :open do |event|
    p [:open]
    # send ping command
    # send test command
    #ws.send({command: 'test'}.to_json)
  end 

  ws.on :message do |event|
    # here is the entry point for data coming from the server.
    p JSON.parse(event.data)
  end 

  ws.on :close do |event|
    # connection has been closed callback.
    p [:close, event.code, event.reason]
    ws = nil 
  end 

Once the client is idle for 2 hours, the server closes the connection. I can't seem to find a way to reconnect to the server once ws.on :close is triggered. Is there an easy way of going about this? I just want it to trigger ws.on :open after :close goes off.

like image 837
randombits Avatar asked Apr 08 '14 15:04

randombits


People also ask

How do I reconnect to WebSocket after closing connection?

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object's onclose method to a function that reconnects after a set timeout. const connect = () => { const ws = new WebSocket("ws://localhost:8080"); ws.

Can I reopen a closed WebSocket?

Just make a new WebSocket again. The reason a reconnect doesn't exist is because it would probably be just like creating a new one. Possible duplicate of Reconnection of client when the server reboots in WebSocket.


1 Answers

Looking for the Faye Websocket Client implementation, there is a ping option which sends some data to the server periodically, which prevents the connection to go idle.

# Send ping data each minute
ws = Faye::WebSocket::Client.new(url, nil, headers: headers, ping: 60) 

However, if you don't want to rely on the server behaviour, since it can finish the connection even if you are sending some data periodically, you can just put the client setup inside a method and start all over again if the server closes the connection.

def start_connection
  ws = Faye::WebSocket::Client.new(url, nil, headers: headers, ping: 60)

  ws.on :open do |event|
    p [:open]
  end 

  ws.on :message do |event|
    # here is the entry point for data coming from the server.
    p JSON.parse(event.data)
  end 

  ws.on :close do |event|
    # connection has been closed callback.
    p [:close, event.code, event.reason]

    # restart the connection
    start_connection
  end
end
like image 69
Thiago Lewin Avatar answered Nov 06 '22 04:11

Thiago Lewin