Skip to content

Instantly share code, notes, and snippets.

@weapp
Forked from maccman/juggernaut.rb
Created May 24, 2014 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weapp/a33847fc30e098c80e85 to your computer and use it in GitHub Desktop.
Save weapp/a33847fc30e098c80e85 to your computer and use it in GitHub Desktop.
# Usage: redis-cli publish message hello
require 'sinatra'
require 'redis'
conns = []
get '/' do
erb :index
end
get '/subscribe' do
content_type 'text/event-stream'
stream(:keep_open) do |out|
conns << out
out.callback { conns.delete(out) }
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.each do |out|
out << "event: #{channel}\n\n"
out << "data: #{message}\n\n"
end
end
end
end
__END__
@@ index
<article id="log"></article>
<script>
var source = new EventSource('/subscribe');
source.addEventListener('message', function (event) {
log.innerText += '\n' + event.data;
}, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment