我要发一个
"Keep alive from client"
每 30 秒为我的 websocket 连接发送一条消息。这是我的 websocket 初始化程序中的代码:
ws = WebSocket::Client::Simple.connect 'wss://bitcoin.toshi.io/'
ws.on :message do |msg|
rawJson = msg.data
message_response = JSON.parse(rawJson)
end
ws.on :open do
ws.send "{\"subscribe\":\"blocks\"}"
end
ws.on :close do |e|
puts "WEBSOCKET HAS CLOSED #{e}"
exit 1
end
ws.on :error do |e|
puts "WEBSOCKET ERROR #{e}"
end
如果没有任何类型的“保持事件状态”,连接将在大约 45 秒内关闭。我应该如何发送“心跳”数据包?看来连接被他们的服务器关闭了,而不是我的。
最佳答案
您可以使用 Websocket Eventmachine Client gem 发送心跳:
require 'websocket-eventmachine-client'
EM.run do
ws = WebSocket::EventMachine::Client.connect(:uri => 'wss://bitcoin.toshi.io/')
puts ws.comm_inactivity_timeout
ws.onopen do
puts "Connected"
end
ws.onmessage do |msg, type|
puts "Received message: #{msg}"
end
ws.onclose do |code, reason|
puts "Disconnected with status code: #{code}"
end
EventMachine.add_periodic_timer(15) do
ws.send "{}"
end
end
您可以使用 EM::add_periodic_timer(interval_in_seconds)
为 EventMachine 设置定时器,然后用它发送您的心跳。
关于ruby-on-rails - 如何在 ruby on rails 中通过 websocket 发送一个 keep-alive 数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31819558/