如何在Rails中通过WebSocket发送保持活动的数据包 [英] How to send a keep-alive packet through websocket in ruby on rails

查看:194
本文介绍了如何在Rails中通过WebSocket发送保持活动的数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要发送

与客户保持联系"

"Keep alive from client"

每30秒发送一次

消息,以进行我的websocket连接.这是我的websocket初始化程序中的代码如下:

message every 30 seconds for my websocket connection. Here's what the code that I have in my websocket initializer looks like:

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秒内关闭.我应该如何发送心跳"数据包?看来该连接是由他们的服务器而不是我的服务器关闭的.

Without any sort of 'keep alive', the connect closes in about 45 seconds. How should I send the 'heart-beat' packet? It seems that the connection is closed by their server, not mine.

推荐答案

您可以使用 Websocket Eventmachine客户端宝石发送听音:

You can use Websocket Eventmachine Client gem to send hearbeat:

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的计时器,然后使用它发送您的心跳.

You can setup timer for EventMachine with EM::add_periodic_timer(interval_in_seconds), and then send your heartbeat with it.

这篇关于如何在Rails中通过WebSocket发送保持活动的数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆