Skip to content

Instantly share code, notes, and snippets.

@rkh
Forked from blambeau/Gemfile
Created December 14, 2011 11:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rkh/1476182 to your computer and use it in GitHub Desktop.
Save rkh/1476182 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. How can 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?

To run it:

bundle install
bundle exec ruby app.rb

Then, try to implement the requested feature. See index.html

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() {
var src = new EventSource('/bottles');
src.onmessage = function(e) { $('#bottles-output').append("\n" + e.data) };
});
</script>
</body>
</html>
@simao
Copy link

simao commented Jan 10, 2013

I am trying to run this with thin but I always get this error:

/home/simao/.rvm/gems/ruby-1.9.3-p327@sp_mpr/gems/sinatra-contrib-1.3.2/lib/sinatra/streaming.rb:119:in `<<': not opened for writing (IOError)
    from /home/simao/sp/mpr/app.rb:69:in `block (3 levels) in <class:MprApp>'
    from /home/simao/sp/mpr/app.rb:68:in `times'
    from /home/simao/sp/mpr/app.rb:68:in `block (2 levels) in <class:MprApp>'
    from /home/simao/.rvm/gems/ruby-1.9.3-p327@sp_mpr/gems/sinatra-1.3.3/lib/sinatra/base.rb:345:in `block (2 levels) in stream'
    from /home/simao/.rvm/gems/ruby-1.9.3-p327@sp_mpr/gems/sinatra-1.3.3/lib/sinatra/base.rb:535:in `with_params'

Do you know what can cause this?

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment