如何通过rails上的ruby中的websocket发送保活包

我想寄一个

“让客户保持活力”

我的websocket连接每30秒发送一条消息。 这是我在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设置计时器,然后使用它发送心跳。

如果您使用的是Iodine的 Websocket客户端,您可以使用自动pingfunction(默认设置,无法关闭):

 require 'iodine/http' # prevents the Iodine's server from running Iodine.protocol = :timer # starts Iodine while the script is still running Iodine.force_start! # set pinging to a 40 seconds interval. Iodine::Http::Websockets.default_timeout = 40 settings = {} # set's the #on_open event callback. settings[:on_open] = Proc.new do write 'sending this connection string.' end # set's the #on_message(data) event callback. settings[:on_message] = Proc.new { |data| puts "Received message: #{data}" } # connects to the websocket Iodine::Http.ws_connect 'ws://localhost:8080', settings 

它是一个相当基本的客户端,但也易于管理。

编辑

Iodine还包括一些cookie和自定义标题的支持,如Iodine的文档中所示 。 因此可以使用不同的身份validation技术(身份validation标头或Cookie)。

Interesting Posts