Skip to content

Instantly share code, notes, and snippets.

@gar
Created January 22, 2012 10:17
Show Gist options
  • Save gar/1656482 to your computer and use it in GitHub Desktop.
Save gar/1656482 to your computer and use it in GitHub Desktop.
Streaming example from Sinatra: Up and Running
# based on Heroku's documentation
require './streaming'
run Sinatra::Application
Request URL:http://0.0.0.0:8080/consume
Request Method:GET
Status Code:200 OK
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en;q=0.8,en-US;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Host:0.0.0.0:8080
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7
Response Headers
Connection:close
Content-Type:text/plain;charset=utf-8
Date:Sun, 22 Jan 2012 11:14:05 GMT
Status:200 OK
Transfer-Encoding:chunked
X-Frame-Options:sameorigin
X-XSS-Protection:1; mode=block
require 'sinatra'
before do
content_type :txt
end
connections = []
get '/consume' do
stream(:keep_open) do |out|
connections << out
out.callback { connections.delete(out) }
out.errback do
logger.warn 'we just lost a connection!'
connections.delete(out)
end
end
end
get '/broadcast/:message' do
connections.each do |out|
out << "#{Time.now} -> #{params[:message]}" << "\n"
end
"Sent #{params[:message]} to all clients."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment