Skip to content

Instantly share code, notes, and snippets.

@blambeau
Created December 14, 2011 10:54
Show Gist options
  • Save blambeau/1476112 to your computer and use it in GitHub Desktop.
Save blambeau/1476112 to your computer and use it in GitHub Desktop.
jquery-sinatra-streaming

jQuery + Sinatra + Streaming

A server-side service outputs a long response using Sinatra's streaming API. The javascript client process this long response as a stream and refresh a pre in the HTML page until the whole response has been received.

The solution implemented here is due to @konstantinhaase. An somewhat uncomplete solution by @hearlamb and not relying on HTML5 EventSource can be found at https://gist.github.com/1476274

To run this one:

bundle install
bundle exec ruby app.rb
require 'sinatra'
set :server, :thin
get '/' do
send_file "index.html"
end
get '/bottles' do
content_type "text/event-stream"
stream do |out|
1000.times do |i|
out << "data: #{i} bottle(s) on a wall...\n\n"
sleep 0.5
end
end
end
source "http://rubygems.org/"
gem "sinatra", "~> 1.3.0"
gem "thin"
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Sinatra streaming example</title>
<meta charset="utf-8" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</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() {
// thanks to @konstantinhaase for this nice HTML5 solution!
var src = new EventSource('/bottles');
src.onmessage = function(e) { $('#bottles-output').append("\n" + e.data) };
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment