class EventMachine::RocketIO::Client

Constants

VERSION

Attributes

channel[R]
io[R]
settings[R]
type[R]

Public Class Methods

new(url, opt={:type => :websocket, :channel => nil}) click to toggle source
# File lib/em-rocketio-client/client.rb, line 15
def initialize(url, opt={:type => :websocket, :channel => nil})
  @url = url
  @type = opt[:type].to_sym
  @channel = opt[:channel] ? opt[:channel].to_s : nil
  @settings = nil
  @io = nil
  @ws_close_timer = nil
  on :__connect do
    io.push :__channel_id, channel
    emit :connect
  end
  get_settings
  self
end
settings() click to toggle source
# File lib/em-rocketio-client/client.rb, line 10
def self.settings
  @@settings ||= {}
end

Public Instance Methods

close() click to toggle source
# File lib/em-rocketio-client/client.rb, line 96
def close
  @io.close
end
connect() click to toggle source
# File lib/em-rocketio-client/client.rb, line 64
def connect
  this = self
  once :__settings do
    if @type == :websocket and @settings.include? 'websocket'
      @io = EM::WebSocketIO::Client.new(@settings['websocket']).connect
    elsif @type == :comet or @settings.include? 'comet'
      @io = EM::CometIO::Client.new(@settings['comet']).connect
      @type = :comet
    else
      raise Error, "cannnot found #{@type} IO"
    end
    @io.on :* do |event_name, *args|
      event_name = :__connect if event_name == :connect
      this.emit event_name, *args
    end
    if @type == :websocket
      @ws_close_timer = EM::add_timer 3 do
        close
        emit :error, "websocket port is not open"
        @type = :comet
        connect
      end
      once :connect do
        EM::cancel_timer @ws_close_timer if @ws_close_timer
        @ws_close_timer = nil
      end
    end
  end
  emit :__settings if @settings
  self
end
method_missing(name, *args) click to toggle source
# File lib/em-rocketio-client/client.rb, line 104
def method_missing(name, *args)
  @io.__send__ name, *args
end
push(type, data={}) click to toggle source
# File lib/em-rocketio-client/client.rb, line 100
def push(type, data={})
  @io.push type, data if @io
end

Private Instance Methods

get_settings() click to toggle source
# File lib/em-rocketio-client/client.rb, line 31
def get_settings
  if self.class.settings[@url].kind_of? Hash
    @settings = self.class.settings[@url]
    emit :__settings
    return
  end
  url = "#{@url}/rocketio/settings"
  http = EM::HttpRequest.new(url).get
  http.callback do |res|
    begin
      @settings = JSON.parse res.response
      self.class.settings[@url] = @settings
      emit :__settings
    rescue => e
      emit :error, "#{e} (#{url})"
      EM::add_timer 10 do
        get_settings
      end
    end
  end
  http.errback do |e|
    if e.error == Errno::ECONNREFUSED
      emit :error, "connection refused (#{url})"
    else
      emit :error, "#{e.error} (#{url})"
    end
    EM::add_timer 10 do
      get_settings
    end
  end
end