Module: Faye::WebSocket::API

Includes:
EventTarget, ReadyStates
Included in:
EventSource, Faye::WebSocket, Client
Defined in:
lib/faye/websocket/api.rb,
lib/faye/websocket/api/event.rb,
lib/faye/websocket/api/event_target.rb

Defined Under Namespace

Modules: EventTarget, ReadyStates Classes: Event, IllegalStateError

Constant Summary

Constants included from ReadyStates

ReadyStates::CLOSED, ReadyStates::CLOSING, ReadyStates::CONNECTING, ReadyStates::OPEN

Instance Attribute Summary collapse

Attributes included from EventTarget

#onclose, #onerror, #onmessage, #onopen

Instance Method Summary collapse

Methods included from EventTarget

#add_event_listener, #dispatch_event, #remove_event_listener

Instance Attribute Details

#buffered_amountObject (readonly)

Returns the value of attribute buffered_amount.



20
21
22
# File 'lib/faye/websocket/api.rb', line 20

def buffered_amount
  @buffered_amount
end

#ready_stateObject (readonly)

Returns the value of attribute ready_state.



20
21
22
# File 'lib/faye/websocket/api.rb', line 20

def ready_state
  @ready_state
end

#urlObject (readonly)

Returns the value of attribute url.



20
21
22
# File 'lib/faye/websocket/api.rb', line 20

def url
  @url
end

Instance Method Details

#close(code = nil, reason = nil, ack = true) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/faye/websocket/api.rb', line 67

def close(code = nil, reason = nil, ack = true)
  return if [CLOSING, CLOSED].include?(@ready_state)
  
  @ready_state = CLOSING
  
  close = lambda do
    @ready_state = CLOSED
    EventMachine.cancel_timer(@ping_timer) if @ping_timer
    @stream.close_connection_after_writing
    event = Event.new('close', :code => code || 1000, :reason => reason || '')
    event.init_event('close', false, false)
    dispatch_event(event)
  end
  
  if ack
    if @parser.respond_to?(:close)
      @parser.close(code, reason, &close)
    else
      close.call
    end
  else
    @parser.close(code, reason) if @parser.respond_to?(:close)
    close.call
  end
end

#receive(data) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/faye/websocket/api.rb', line 40

def receive(data)
  return false unless @ready_state == OPEN
  event = Event.new('message')
  event.init_event('message', false, false)
  event.data = data
  dispatch_event(event)
end

#send(data, type = nil, error_type = nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/faye/websocket/api.rb', line 48

def send(data, type = nil, error_type = nil)
  if @ready_state == CONNECTING
    if @send_buffer
      @send_buffer << [data, type, error_type]
      return true
    else
      raise IllegalStateError, 'Cannot call send(), socket is not open yet'
    end
  end
  
  return false if @ready_state == CLOSED
  
  data = data.to_s unless Array === data
  
  data = WebSocket.encode(data) if String === data
  frame = @parser.frame(data, type, error_type)
  @stream.write(frame) if frame
end