require 'rubygems' require 'bundler/setup' require 'reel' require 'celluloid/autostart' class TimeServer include Celluloid include Celluloid::Notifications def initialize run! end def run now = Time.now.to_f sleep now.ceil - now + 0.001 every(1) { publish 'time_change', Time.now } end end class TimeClient include Celluloid include Celluloid::Notifications include Celluloid::Logger def initialize(websocket) info "Streaming time changes to client" @socket = websocket subscribe('time_change', :notify_time_change) end def notify_time_change(topic, new_time) @socket << new_time.inspect rescue Reel::SocketError info "Time client disconnected" terminate end end class Web include Celluloid::Logger def render_index info "200 OK: /" <<-HTML Reel WebSockets time server example

Time Server Example

The time is now: ...
HTML end end TimeServer.supervise_as :time_server run Rack::URLMap.new( "/" => Proc.new{ [200, {"Content-Type" => "text/html"}, [Web.new.render_index]]}, "/timeinfo" => Proc.new{ |env| TimeClient.new(env["websocket.rack"]) [200, {}, []] # Fake response for middleware. } )