public
Last active

Sinatra Server Side Event streaming with private channels.

  • Download Gist
juggernaut_channels.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# Usage: redis-cli publish message.achannel hello
 
require 'sinatra'
require 'redis'
 
conns = Hash.new {|h, k| h[k] = [] }
 
Thread.abort_on_exception = true
 
get '/' do
erb :index
end
 
get '/subscribe/:channel' do
content_type 'text/event-stream'
 
stream(:keep_open) do |out|
channel = params[:channel]
 
conns[channel] << out
 
out.callback do
conns[channel].delete(out)
end
end
end
 
Thread.new do
redis = Redis.connect
 
redis.psubscribe('message', 'message.*') do |on|
on.pmessage do |match, channel, message|
channel = channel.sub('message.', '')
 
conns[channel].each do |out|
out << "data: #{message}\n\n"
end
end
end
end
 
__END__
 
@@ index
<article id="log"></article>
 
<script>
var source = new EventSource('/subscribe/achannel');
 
source.addEventListener('message', function (event) {
log.innerText += '\n' + event.data;
}, false);
</script>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.