Created
March 10, 2012 17:57
-
-
Save chatgris/2012299 to your computer and use it in GitHub Desktop.
Playing with Sinatra streaming api.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
require 'bundler' | |
Bundler.require | |
require './server' | |
run App |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source :rubygems | |
gem 'sinatra', git: 'git://github.com/sinatra/sinatra.git' | |
gem 'thin' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
require 'sinatra/base' | |
class Connections | |
include Enumerable | |
def initialize | |
@connections = {} | |
end | |
def []=(id, connection) | |
# Set on_close callback | |
connection.callback { leave(id)} | |
@connections[id] = connection | |
end | |
def [](id) | |
@connections[id] | |
end | |
def each(&block) | |
@connections.values.each &block | |
end | |
def delete(id) | |
@connections.delete id | |
end | |
def join(id, connection) | |
broadcast "#{id} joins" | |
self[id] = connection | |
send(id, "Hello #{id}") | |
end | |
def leave(id) | |
delete id | |
broadcast "#{id} left" | |
end | |
def send(id, message) | |
self[id] << message << "\n" if self[id] | |
end | |
def broadcast(message) | |
each {|connection| connection << message << "\n"} | |
end | |
def connected | |
@connections.keys | |
end | |
end | |
class App < Sinatra::Base | |
set :port, ARGV[1] || 4567 | |
set :server, :thin | |
connections = Connections.new | |
helpers do | |
def user | |
@user ||= ['Gaston', 'Hervé', 'Bill', 'Totoro', 'Mei', 'Fred', 'Alex', 'Chou', 'Fleur', 'Jean'].sample | |
end | |
end | |
get '/' do | |
# stream to all users | |
connections.broadcast(connections.connected) | |
# stream to one perticular user | |
connections.send(user, user) | |
# Return list of current connected users | |
connections.connected.join(', ') | |
end | |
get '/stream', provides: 'text/event-stream' do | |
stream(:keep_open) {|connection| connections.join(user, connection) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment