public
Last active

Sinatra streaming + Redis PubSub

  • Download Gist
Gemfile
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
source 'https://rubygems.org'
 
gem 'sinatra'
gem 'sinatra-contrib', require: 'sinatra/streaming'
 
group :development do
gem 'thin'
gem 'pry-rails'
end
 
gem 'eventmachine', "= 1.0.0.rc.4"
gem "redis", "~> 3.0"
gem "hiredis", "~> 0.4.5"
gem 'em-hiredis'
app.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
require 'bundler'
Bundler.require
 
class App < Sinatra::Base
helpers Sinatra::Streaming
 
get '/' do
subscriber = EM::Hiredis.connect
subscriber.psubscribe '*'
 
stream :keep_open do |out|
subscriber.on(:pmessage) do |key, channel, message|
subscriber.punsubscribe '*' if out.closed?
 
out << "#{key}, #{channel}, #{message}" unless out.closed?
end
end
end
end

Example client code (JS)

var xhr = new XMLHttpRequest()
xhr.open("GET", "/", true)
xhr.onprogress = function () {
  alert(xhr.responseText)
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.