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

时间:2014-04-08 15:10:42

标签: ruby websocket eventmachine 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 

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

1 个答案:

答案 0 :(得分:10)

在寻找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