Skip to content

Instantly share code, notes, and snippets.

@makevoid
Forked from maccman/juggernaut.rb
Last active August 29, 2015 14:27
Show Gist options
  • Save makevoid/7bad51167053353ea5ed to your computer and use it in GitHub Desktop.
Save makevoid/7bad51167053353ea5ed to your computer and use it in GitHub Desktop.
Sinatra Server Side Event streaming.
# 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| # EventMachine?
conns << out
out.callback { conns.delete(out) }
end
end
Thread.new do
redis = Redis.connect#, db: 0
redis.psubscribe('message', 'message.*') do |on|
on.pmessage do |match, channel, message|
channel = channel.sub 'example message.', ''
conns.each do |out|
out << "event: #{channel}\n"
out << "data: #{message}\n"
end
end
end
end
__END__
# view
@@ index
# TODO: load opal
<article id="log"></article>
# client code is written and served by the server
<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