Class: EventMachine::WebSocketIO::Client

Inherits:
Object
  • Object
show all
Includes:
EventEmitter
Defined in:
lib/em-websocketio-client.rb,
lib/em-websocketio-client/client.rb,
lib/em-websocketio-client/version.rb

Constant Summary collapse

VERSION =
"0.0.4"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
# File 'lib/em-websocketio-client/client.rb', line 8

def initialize(url)
  raise ArgumentError, "invalid websocket URL \"#{url}\"" unless url =~ /^ws:\/\/.+/
  @url = url
  @running = false
  @__reconnect_timer_id = nil
  @ws = nil
  self.on :__session_id do |session_id|
    @session = session_id
    self.emit :connect, session_id
  end
end

Instance Attribute Details

#runningObject (readonly)

Returns the value of attribute running.



5
6
7
# File 'lib/em-websocketio-client/client.rb', line 5

def running
  @running
end

#sessionObject (readonly)

Returns the value of attribute session.



5
6
7
# File 'lib/em-websocketio-client/client.rb', line 5

def session
  @session
end

#timeoutObject

Returns the value of attribute timeout.



6
7
8
# File 'lib/em-websocketio-client/client.rb', line 6

def timeout
  @timeout
end

#urlObject (readonly)

Returns the value of attribute url.



5
6
7
# File 'lib/em-websocketio-client/client.rb', line 5

def url
  @url
end

Instance Method Details

#closeObject



50
51
52
53
54
# File 'lib/em-websocketio-client/client.rb', line 50

def close
  @running = false
  @ws.close_connection if @ws
  EM::cancel_timer @__reconnect_timer_id
end

#connectObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/em-websocketio-client/client.rb', line 20

def connect
  url = @session ? "#{@url}/session=#{@session}" : @url
  @ws = EventMachine::WebSocketClient.connect url
  @running = true

  @ws.stream do |msg|
    data = JSON.parse msg.data
    self.emit data['type'], data['data']
  end

  @ws.callback do
    self.push :__session_id
  end

  @ws.errback do |err|
    self.emit :error, err
  end

  @ws.disconnect do
    self.emit :disconnect
    if @running
      @__reconnect_timer_id = EM::add_timer 10 do
        connect
      end
    end
  end

  return self
end

#push(type, data = {}) ⇒ Object



56
57
58
# File 'lib/em-websocketio-client/client.rb', line 56

def push(type, data={})
  @ws.send_msg({:type => type, :data => data, :session => self.session}.to_json)
end