Class: Faye::WebSocket::Client

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
API
Defined in:
lib/faye/websocket/client.rb

Defined Under Namespace

Modules: Connection

Constant Summary collapse

DEFAULT_PORTS =
{'http' => 80, 'https' => 443, 'ws' => 80, 'wss' => 443}
SECURE_PROTOCOLS =
['https', 'wss']

Constants included from API

API::CLOSED, API::CLOSING, API::CONNECTING, API::OPEN, API::TYPES

Instance Attribute Summary

Attributes included from API

#buffered_amount, #ready_state, #url

Instance Method Summary collapse

Methods included from API

#close, #ping, #protocol, #send, #write

Methods included from API::EventTarget

#add_event_listener, #add_listener, #dispatch_event, #remove_event_listener

Constructor Details

#initialize(url, protocols = nil, options = {}) ⇒ Client

Returns a new instance of Client.


15
16
17
18
19
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
49
50
51
52
53
54
55
56
# File 'lib/faye/websocket/client.rb', line 15

def initialize(url, protocols = nil, options = {})
  @url = url
  super(options) { ::WebSocket::Driver.client(self, :max_length => options[:max_length], :protocols => protocols) }

  proxy       = options.fetch(:proxy, {})
  endpoint    = URI.parse(proxy[:origin] || @url)
  port        = endpoint.port || DEFAULT_PORTS[endpoint.scheme]
  @secure     = SECURE_PROTOCOLS.include?(endpoint.scheme)
  @origin_tls = options.fetch(:tls, {})
  @socket_tls = proxy[:origin] ? proxy.fetch(:tls, {}) : @origin_tls

  if proxy[:origin]
    @proxy = @driver.proxy(proxy[:origin])
    if headers = proxy[:headers]
      headers.each { |name, value| @proxy.set_header(name, value) }
    end

    @proxy.on(:connect) do
      uri    = URI.parse(@url)
      secure = SECURE_PROTOCOLS.include?(uri.scheme)
      @proxy = nil

      if secure
        origin_tls = {:sni_hostname => uri.host}.merge(@origin_tls)
        @stream.start_tls(origin_tls)
      end

      @driver.start
    end

    @proxy.on(:error) do |error|
      @driver.emit(:error, error)
    end
  end

  EventMachine.connect(endpoint.host, port, Connection) do |conn|
    conn.parent = self
  end
rescue => error
  emit_error("Network error: #{url}: #{error.message}")
  finalize_close
end