Faye WebSocket,在关闭处理程序被触发后重新连接到套接字

ran*_*its 5 ruby eventmachine websocket faye

我有一个超级简单的脚本,它在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 
Run Code Online (Sandbox Code Playgroud)

客户端空闲2小时后,服务器将关闭连接.一旦ws.on :close触发,我似乎无法找到重新连接到服务器的方法.有一个简单的方法来解决这个问题吗?我只是希望它在启动ws.on :open后触发:close.

Thi*_*win 10

寻找Faye Websocket客户端实现,有一个ping选项可以定期向服务器发送一些数据,这可以防止连接空闲.

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

但是,如果您不想依赖服务器行为,即使您定期发送一些数据也可以完成连接,您可以将客户端设置放在方法中,如果服务器关闭,则重新开始连接.

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
Run Code Online (Sandbox Code Playgroud)