Sinatra: Up and Running by Alan Harris & Konstantin Haase

Sinatra: Up and Running by Alan Harris & Konstantin Haase

Author:Alan Harris & Konstantin Haase [Alan Harris]
Language: eng
Format: epub, pdf
Tags: COMPUTERS / Programming Languages / Ruby
ISBN: 9781449304225
Publisher: O'Reilly Media
Published: 2011-11-22T05:00:00+00:00


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



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.