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?
Here is my controller:
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