lib/faye/websocket/client.rb in faye-websocket-0.7.5 vs lib/faye/websocket/client.rb in faye-websocket-0.8.0

- old
+ new

@@ -2,13 +2,17 @@ class WebSocket class Client include API + DEFAULT_PORTS = {'http' => 80, 'https' => 443, 'ws' => 80, 'wss' => 443} + SECURE_PROTOCOLS = ['https', 'wss'] + attr_reader :headers, :status def initialize(url, protocols = nil, options = {}) + @url = url @driver = ::WebSocket::Driver.client(self, :max_length => options[:max_length], :protocols => protocols) [:open, :error].each do |event| @driver.on(event) do @headers = @driver.headers @@ -16,29 +20,53 @@ end end super(options) - @url = url - @uri = URI.parse(url) + 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 - port = @uri.port || (@uri.scheme == 'wss' ? 443 : 80) - EventMachine.connect(@uri.host, port, Connection) do |conn| + 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 + + @stream.start_tls(@origin_tls) if secure + @driver.start + end + + @proxy.on(:error) do |error| + @driver.emit(:error, error) + end + end + + EventMachine.connect(endpoint.host, port, Connection) do |conn| @stream = conn conn.parent = self end rescue => error event = Event.create('error', :message => "Network error: #{url}: #{error.message}") event.init_event('error', false, false) dispatch_event(event) - finalize(error.message, 1006) + finalize('', 1006) end private - def on_connect - @stream.start_tls if @uri.scheme == 'wss' - @driver.start + def on_connect() + @stream.start_tls(@socket_tls) if @secure + worker = @proxy || @driver + worker.start end module Connection attr_accessor :parent