[~/local/src/ruby/sinatra/sinatra-streaming/jquery-streaming(master)]$ pwd -P /Users/casiano/local/src/ruby/sinatra/sinatra-streaming/jquery-streaming
[~/local/src/ruby/sinatra/sinatra-streaming/jquery-streaming(master)]$ cat app.rb require 'sinatra' require 'pp' set :server, :thin get '/' do send_file "index.html" end get '/bottles' do content_type "text/event-stream" stream do |out| 0.upto(50) do |i| out << "id: #{i}\n" out << "data: #{i} bottle(s) on a wall...\n\n" sleep 0.3 end out << "data: CLOSE\n\n" end end
[~/local/src/ruby/sinatra/sinatra-streaming/jquery-streaming(master)]$ cat index.html <!DOCTYPE html> <html> <head> <title>Sinatra streaming example</title> <meta charset="utf-8" /> <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script> <style>body {font-family: sans-serif;}</style> </head> <body> <h1>Welcome to this Sinatra Streaming example!</h1> <input id="bottles-button" type="button" value="Bottles!"/> <pre id="bottles-output"> </pre> <script> $("#bottles-button").click(function() { var src = new EventSource('/bottles?foo=bar'); src.onmessage = function(e) { console.log(e) $('#bottles-output').append("\n" + e.data) if ( e.data == 'CLOSE' ) src.close() }; }); </script> </body> </html>