Sha256: 4f4381159c6bad17dc91b2f87137d7c71a98b6fd97051ec1dade20e537bbd592

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 KB

Contents

module Sinatra
  module CometIO

    def self.sessions
      @@sessions ||= Hash.new{|h,session_id|
        h[session_id] = {
          :queue => [{:type => :__session_id, :data => session_id}],
          :stream => nil,
          :last => nil
        }
      }
    end

    def self.gc
      self.sessions.each do |id, s|
        next unless s[:last] and s[:last] < Time.now-CometIO.options[:timeout]*2-10
        self.sessions.delete id rescue next
        self.emit :disconnect, id
      end
    end

    EM::defer do
      loop do
        self.gc
        sleep CometIO.options[:timeout]+5
      end
    end

    def self.push(type, data, opt={})
      if opt.include? :to and self.sessions.include? opt[:to]
        s = self.sessions[opt[:to]]
        if s[:queue].empty? and s[:stream] != nil
          begin
            s[:stream].write([{:type => type, :data => data}].to_json)
            s[:stream].flush
            s[:stream].close
          rescue
            s[:stream].close
            s[:queue].push :type => type, :data => data
          end
        else
          s[:queue].push :type => type, :data => data
        end
      else
        self.sessions.keys.each do |id|
          push type, data, :to => id
        end
      end
    end

    def self.create_session(ip_addr)
      Digest::MD5.hexdigest "#{Time.now.to_i}_#{Time.now.usec}_#{ip_addr}"
    end

  end
end
EventEmitter.apply Sinatra::CometIO

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sinatra-cometio-0.4.2 lib/sinatra-cometio/cometio.rb