我有一个超级简单的脚本,它几乎包含了Faye WebSocket GitHub页面上用于处理关闭连接的内容:
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
一旦客户端空闲2小时,服务器就会关闭连接。一旦触发ws.on :close
,我似乎找不到重新连接到服务器的方法。有什么简单的方法吗?我只想让它在:close
关闭后触发ws.on :open
。
在寻找Faye Websocket客户端实现时,有一个ping
选项可以定期向服务器发送一些数据,从而防止连接空闲。
# Send ping data each minute
ws = Faye::WebSocket::Client.new(url, nil, headers: headers, ping: 60)
然而,如果你不想依赖服务器的行为,因为即使你定期发送一些数据,它也可以完成连接,你可以把客户端设置放在一个方法中,如果服务器关闭连接,就可以重新开始。
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