Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Fundamentals > Streaming

Streaming

One of the most exciting new features in Sinatra (version 1.3.0 and up) is support for content streaming from your application. The streaming support abstracts away the differences in different Rack-compatible servers, leaving you to focus solely on developing the functionality you desire as opposed to the plumbing that makes it possible.

Keeping the Connection Open

There are a number of applications that lend themselves to a persistent, open connection. Perhaps you’re developing a chat program or something similar; Example 2-37 shows how to create this type of connection and broadcast messages to subscribers.

Example 2-37. A simple streaming example
require 'sinatra'

before do
  content_type :txt
end

connections = []

get '/consume' do
  stream(:keep_open) do |out|
    # store connection for later on
    connections << out

    # remove connection when closed properly
    out.callback { connections.delete(out) }

    # remove connection when closed due to an error
    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

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint