Created
June 26, 2012 02:49
-
-
Save maccman/2992949 to your computer and use it in GitHub Desktop.
Sinatra Server Side Event streaming.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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
Thank you for that inspiration, I almost used faye..
There is a typo (?) in line 27, there should be only one newline to keep both lines close together:
Else the pushed message won't have the right
type
bound, andsource.addEventListener('different'..)
won't react at all.