ruby-on-rails – 如何通过rails上的ruby中的websocket发送保持
发布时间:2020-12-17 02:24:32 所属栏目:百科 来源:网络整理
导读:我想送一个 “Keep alive from client” 我的websocket连接每30秒发送一条消息.这是我在websocket初始化程序中的代码如下所示: ws = WebSocket::Client::Simple.connect 'wss://bitcoin.toshi.io/'ws.on :message do |msg| rawJson = msg.data message_resp
我想送一个
我的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设置计时器,然后使用它发送心跳. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |