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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With