ActionController::Live 是否可以检查连接是否仍然存在? [英] ActionController::Live Is it possible to check if connection is still alive?
问题描述
我正在尝试使用 Rails 4 的实时流来实现文本/事件流.它工作得很好,我遇到的唯一问题是我无法在不发送任何消息的情况下检查连接是否有效.
I'm trying to implement text/event-stream using Rails 4's Live streaming. It works great and the only trouble I met is that I can't check if the connection is alive without sending any messages.
我想出的唯一解决方案是使用循环滴答生成器制作支持频道,以便某些后台任务会定期向那里发送消息.但它似乎是凌乱和不可靠的.有什么更好的解决方案吗?
The only solution I figured out is to make supportive channel with cyclic tick generator, so that some background task will send messages there periodically. But it seems to be messy and non-reliable. Any better solutions?
这是我的控制器:
require 'persistency/sse'
require 'persistency/track'
class PersistencyController < ApplicationController
include ActionController::Live
def stream
response.headers['Content-Type'] = 'text/event-stream'
sse = Persistency::SSE.new(response.stream)
track = Persistency::Track.new(current_user)
redis = Redis.new
begin
redis.subscribe(:info, :chat) do |on|
on.message do |channel, message|
sse.write({ :message => message }, :event => channel)
end
end
rescue IOError
ensure
track.close
sse.close
end
end
end
推荐答案
好的,我找到了两个选项:
Ok, I found two options:
1) 有趣但不好(因为我不知道应该使用什么服务器来处理 1000 个并行连接):
1) Funny but not good (as I didn't get what sever should I use to handle 1000's of parallel connections):
begin
ticker = Thread.new { loop { sse.write 0; sleep 5 } }
sender = Thread.new do
redis.subscribe(:info, :chat) do |on|
on.message do |event, message|
sse.write(message, :event => event.to_s)
end
end
end
ticker.join
sender.join
rescue IOError
ensure
Thread.kill(ticker) if ticker
Thread.kill(sender) if sender
track.close
sse.close
end
2) 太棒了.使用歌利亚服务器.原来它可以在没有任何代码的情况下检查连接是否丢失.在去Goliath的路上发现了Cramp.它是轻量级的,希望很快,但似乎被放弃了.
2) Awesome. To use Goliath server. It turned out that it can check if connection is lost without any ticker. On the way to Goliath found Cramp. It's lightweight and hopefully fast, but seems to be abandonned.
这篇关于ActionController::Live 是否可以检查连接是否仍然存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!