Skip to content

Instantly share code, notes, and snippets.

@kubicek
Created May 13, 2015 18:20
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 kubicek/33a936f225e4253b7999 to your computer and use it in GitHub Desktop.
Save kubicek/33a936f225e4253b7999 to your computer and use it in GitHub Desktop.
amqp2sse
# based on https://github.com/cloudamqp/amqp-sse/blob/master/app.rb
require 'sinatra'
require 'sinatra/streaming'
require 'amqp'
configure do
EM.next_tick do
AMQP.connection = AMQP.connect "amqp://guest:guest@localhost"
end
end
get '/' do
erb :index
end
get '/stream/:user_id', provides: 'text/event-stream' do
@user_id=params['user_id']
stream :keep_open do |out|
AMQP::Channel.new do |channel|
channel.queue('', exclusive: true, autodelete: true) do |queue|
queue.bind(channel.headers("amq.match", durable: true), arguments:{ user_id: @user_id }).subscribe do |payload|
out << "data: #{payload}\n\n"
end
end
# add a timer to keep the connection alive
timer = EM.add_periodic_timer(20) { out << ":\n" }
# clean up when the user closes the stream
out.callback do
timer.cancel
channel.close
end
end
end
end
__END__
@@ layout
<html>
<head>
<title>Notification receiver</title>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body><%= yield %></body>
</html>
@@ index
<pre id='notifications'></pre>
<script>
var es = new EventSource('/stream/5434');
es.onmessage = function(e) { $('#notifications').append(e.data + "\n") };
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment