1 var util = require('util'),
5 driver = require('websocket-driver'),
6 API = require('./api'),
7 Event = require('./api/event');
9 var DEFAULT_PORTS = {'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443},
10 SECURE_PROTOCOLS = ['https:', 'wss:'];
12 var Client = function(_url, protocols, options) {
13 options = options || {};
16 this._driver = driver.client(this.url, {maxLength: options.maxLength, protocols: protocols});
18 ['open', 'error'].forEach(function(event) {
19 this._driver.on(event, function() {
20 self.headers = self._driver.headers;
21 self.statusCode = self._driver.statusCode;
25 var proxy = options.proxy || {},
26 endpoint = url.parse(proxy.origin || this.url),
27 port = endpoint.port || DEFAULT_PORTS[endpoint.protocol],
28 secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0,
29 onConnect = function() { self._onConnect() },
30 originTLS = options.tls || {},
31 socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS,
34 originTLS.ca = originTLS.ca || options.ca;
37 ? tls.connect(port, endpoint.hostname, socketTLS, onConnect)
38 : net.connect(port, endpoint.hostname, onConnect);
40 if (proxy.origin) this._configureProxy(proxy, originTLS);
42 API.call(this, options);
44 util.inherits(Client, API);
46 Client.prototype._onConnect = function() {
47 var worker = this._proxy || this._driver;
51 Client.prototype._configureProxy = function(proxy, originTLS) {
52 var uri = url.parse(this.url),
53 secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0,
57 this._proxy = this._driver.proxy(proxy.origin);
60 for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]);
63 this._proxy.pipe(this._stream, {end: false});
64 this._stream.pipe(this._proxy);
66 this._proxy.on('connect', function() {
68 var options = {socket: self._stream, servername: uri.hostname};
69 for (name in originTLS) options[name] = originTLS[name];
70 self._stream = tls.connect(options);
71 self._configureStream();
73 self._driver.io.pipe(self._stream);
74 self._stream.pipe(self._driver.io);
78 this._proxy.on('error', function(error) {
79 self._driver.emit('error', error);
83 module.exports = Client;