JAVASCRIPT   17

client.js

Guest on 3rd August 2021 11:04:16 AM

  1. var util   = require('util'),
  2.     net    = require('net'),
  3.     tls    = require('tls'),
  4.     driver = require('websocket-driver'),
  5.     API    = require('./api'),
  6.     Event  = require('./api/event');
  7.  
  8. var Client = function(url, protocols, options) {
  9.   options = options || {};
  10.  
  11.   this.url     = url;
  12.   this._uri    = require('url').parse(url);
  13.   this._driver = driver.client(url, {maxLength: options.maxLength, protocols: protocols});
  14.  
  15.   ['open', 'error'].forEach(function(event) {
  16.     this._driver.on(event, function() {
  17.       self.headers    = self._driver.headers;
  18.       self.statusCode = self._driver.statusCode;
  19.     });
  20.   }, this);
  21.  
  22.   var secure     = (this._uri.protocol === 'wss:'),
  23.       onConnect  = function() { self._driver.start() },
  24.       tlsOptions = {},
  25.       self       = this;
  26.  
  27.   if (options.ca) tlsOptions.ca = options.ca;
  28.  
  29.   var connection = secure
  30.                  ? tls.connect(this._uri.port || 443, this._uri.hostname, tlsOptions, onConnect)
  31.                  : net.createConnection(this._uri.port || 80, this._uri.hostname);
  32.  
  33.   this._stream = connection;
  34.   if (!secure) this._stream.on('connect', onConnect);
  35.  
  36.   API.call(this, options);
  37. };
  38. util.inherits(Client, API);
  39.  
  40. module.exports = Client;

Raw Paste


Login or Register to edit or fork this paste. It's free.