illyria client
@param {String} [host] the hostname
@param {Number} [port] the port number
@param {Object} [options] the socket options
@constructor
969056
function(host, port, options) {
    EventEmitter.call(this);

    // we consider this situation is using zookeeper
    if(typeof host === "object") {
        options = host;
        host = port = undefined;
    }

    options = options || {};

    // using zookeeper will ignore `host` and `port`
    if(options.zookeeper) {
        host = port = undefined;

        this.zookeeperOptions = options.zookeeper || {};
        this.zookeeperOptions.connectString = this.zookeeperOptions.connectString || "127.0.0.1:2181";
        this.zookeeperOptions.root = this.zookeeperOptions.root || "/illyria";
        this.zookeeperOptions.prefix = this.zookeeperOptions.prefix || "/HB_";

        if(this.zookeeperOptions.connectString instanceof Array) {
            this.zookeeperOptions.connectString = this.zookeeperOptions.connectString.join(",");
        }

        if(!this.zookeeperOptions.root.startsWith("/")) {
            this.zookeeperOptions.root = "/" + this.zookeeperOptions.root;
        }

        if(!this.zookeeperOptions.prefix.startsWith("/")) {
            this.zookeeperOptions.prefix = "/" + this.zookeeperOptions.prefix;
        }

    }

    this.options = options;
    this.socket = new ISocket(options);
    this.status = "NOT_CONNECTED";

    this.port = port;
    this.host = host;

    this.runTimeout = options.runTimeout || 10000;
    this.msgId = 0;

    this.socket.addListener("error", this.emit.bind(this, "error"));
    this.socket.addListener("close", this.emit.bind(this, "close"));
    this.socket.addListener("tryReconnect", this.emit.bind(this, "tryReconnect"));
    this.socket.addListener("connected", this.emit.bind(this, "connected"));
    
    var self = this;
    this.on("connected", function() {
        self.status = "CONNECTED";
    });
    this.on("tryReconnect", function() {
        self.status = "RECONNECTING";
    });
    this.on("close", function(hadError) {
        if(hadError) {
            if(!process.env.ZK_NO_WARN) console.warn("Illyria client closed with an error.");
        }

        self.status = "DISCONNECTED";
    });
    
    this.on("error", function() {});
}
120353
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    winston.info('Control connection from %s opened', this.socket.remoteAddress);

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}
541343
function RPCClient(options) {
  if (!(this instanceof RPCClient))
    return new RPCClient(options);

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { uri: options };

  this.options = options;
  this.network = Network.get(options.network);

  this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
  this.apiKey = options.apiKey;
  this.id = 0;
}
743348
function Client(opts) {
    if (!(this instanceof Client)) {
        return new Client(opts);
    }

    var options = {};

    // If single connection provided, array-ify it
    if (typeof opts === 'string') {
        options.hosts = [opts];
        opts = options;
    } else if (typeof opts === 'undefined') {
        opts = {};
    } else if (_.isArray(opts)) {
        options.hosts = opts;
        opts = options;
    }

    _.defaults(opts, {
        autodiscover: false,
        bufferBeforeError: 1000,
        disabled: false,
        hosts: null,
        reconnect: true,
        onNetError: function onNetError(err) { console.error(err); },
        queue: true,
        netTimeout: 500,
        backoffLimit: 10000,
        maxValueSize: 1048576
    });

    // Iterate over options, assign each to this object
    R.keys(opts).forEach(function(key) {
        this[key] = opts[key];
    }, this);

    if (this.queue) {
        this.buffer = new Immutable.List();
    }

    debug('Connect options', opts);
    this.connect();
}
202908
function setupListener (host_port, listenerDone) {

            const hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
            if (!hp) return listenerDone(
                new Error('Invalid "listen" format in smtp.ini'));

            const host = hp[1];
            const port = parseInt(hp[2], 10);

            Server.get_smtp_server(host, port, inactivity_timeout, (server) => {
                if (!server) return listenerDone();

                server.notes = Server.notes;
                if (Server.cluster) server.cluster = Server.cluster;

                server
                    .on('listening', function () {
                        const addr = this.address();
                        logger.lognotice(`Listening on ${addr.address}:${addr.port}`);
                        listenerDone();
                    })
                    .on('close', () => {
                        logger.loginfo(`Listener ${host}:${port} stopped`);
                    })
                    .on('error', e => {
                        if (e.code !== 'EAFNOSUPPORT') return listenerDone(e);
                        // Fallback from IPv6 to IPv4 if not supported
                        // But only if we supplied the default of [::0]:25
                        if (/^::0/.test(host) && Server.default_host) {
                            server.listen(port, '0.0.0.0', 0);
                            return;
                        }
                        // Pass error to callback
                        listenerDone(e);
                    })
                    .listen(port, host, 0);
            });
        }
243809
function ProxyHost ( options ) {
	// prepare
	var name;

	// connection with server
	this.active = false;

	/**
	 * proxy instance configuration
	 * @namespace
	 */
	this.config = {
		/** proxy server address */
		host : '127.0.0.1',

		/** proxy server websocket port */
		port : 8900,

		/** session name */
		name : 'anonymous',

		/** automatically try to restore connection on disconnect */
		reconnect : true,

		/** time between connection attempts (5s) */
		reconnectInterval : 5000
	};

	/**
	 * @type {WebSocket}
	 */
	this.socket = null;

	// validate and iterate input
	if ( options && typeof options === 'object' ) {
		for ( name in options ) {
			// rewrite defaults
			if ( options.hasOwnProperty(name) ) { this.config[name] = options[name]; }
		}
	}

	// try to establish connection
	this.connect();
}
1170388
function _cmdSend(idOrArray, msgStr) {
    if (!Array.isArray(idOrArray)) {
        idOrArray = [idOrArray];
    }
    idOrArray.forEach(function (id) {
        var client = _clients[id];
        if (!client) {
            console.error("nodeSocketTransport: Couldn't find client ID: " + id);
        } else {
            client.socket.send(msgStr);
        }
    });
}
9627
function(hostname, callback) {
  get_nodes(function(err,nodes) {
    if (err) return callback(err);

    var n = nodes.filter(function(node) {
      return node.name === hostname;
    });

    callback(null,(n.length === 1) ? n[0].ip_address : null);
  });
}
1334273
function Server(options) {
  var that = this;
  that.options = options || {};
  that.stack = [];
  bind.call(that);
}
668483
function(host, port) {
  var sock = new WebSocket('ws://' + host + ':' + port);
  sock.onopen = function() {
    console.log("Connected to browserify-reload handle");
  }

  sock.onmessage = function(msg){
    if(msg && msg.data == "reload")
      document.location = document.location.href;
  }
}
581701
function(serverUrl) {
  var parsedUrl = url.parse(serverUrl);
  if (!parsedUrl.hostname) {
    throw new Error('Invalid server URL: ' + serverUrl);
  }

  /**
   * Base options for each request.
   * @private {!Object}
   */
  this.options_ = {
    host: parsedUrl.hostname,
    path: parsedUrl.pathname,
    port: parsedUrl.port
  };
}
568625
function() {
      var t = this, hostName = t.get('hostName'), hostPort = t.get('hostPort'),
      url = t.get('url');

      // Build the URL if not specified
      if (!url) {
        url = t.attributes.url = 'http://' + hostName + ':' + hostPort;
        t.set('url', url);
      }

      // Connect with this url
      var opts = {
        // 'transports': ['websocket', 'xhr-polling', 'jsonp-polling'],
        'force new connection': true,      // Don't re-use existing connections
        'reconnect': false                 // Don't let socket.io reconnect.
                                           // Reconnects are performed by the Router.
      };
      var socket = SocketIO.connect(url, opts);
      t.set({socket:socket}).bindConnectionEvents();
    }
735398
function ServerConnection (options) {

    this.log = options.log;
    this.port = options.port;
    this.proxyUrl = options.proxyUrl;

    if (!(options.udp4 === false)) {
        this.listenUDP4();
    }
    if (!(options.tcp === false)) {
        this.listenTCP();
    }
    if (!(options.socketio === false)) {
        this.listenSocketIO();
    }

    EventEmitter.call(this);

}
712881
public static function parse_socket_options(&$options, $host = null)
    {
        if (empty($host) || empty($options)) {
            return $options;
        }

        // get rid of schema and port from the hostname
        $host_url = parse_url($host);
        if (isset($host_url['host'])) {
            $host = $host_url['host'];
        }

        // find per-host options
        if (array_key_exists($host, $options)) {
            $options = $options[$host];
        }
    }
296262
function(ip, options) {
    var self = this;
    this.ip = ip;
    this.openFlag = false;
    this.callback = null;

    // options
    if (typeof options === "undefined") options = {};
    this.port = options.port || TELNET_PORT; // telnet server port

    // internal buffer
    this._buffer = Buffer.alloc(0);
    this._id = 0;
    this._cmd = 0;
    this._length = 0;

    // handle callback - call a callback function only once, for the first event
    // it will triger
    var handleCallback = function(had_error) {
        if (self.callback) {
            self.callback(had_error);
            self.callback = null;
        }
    };

    // create a socket
    this._client = new net.Socket();
    if (options.timeout) this._client.setTimeout(options.timeout);

    // register the port data event
    this._client.on("data", function onData(data) {
        // add data to buffer
        self._buffer = Buffer.concat([self._buffer, data]);

        // check if buffer include a complete modbus answer
        var expectedLength = self._length;
        var bufferLength = self._buffer.length;
        modbusSerialDebug(
            "on data expected length:" +
                expectedLength +
                " buffer length:" +
                bufferLength
        );

        modbusSerialDebug({
            action: "receive tcp telnet port",
            data: data,
            buffer: self._buffer
        });
        modbusSerialDebug(
            JSON.stringify({
                action: "receive tcp telnet port strings",
                data: data,
                buffer: self._buffer
            })
        );

        // check data length
        if (expectedLength < 6 || bufferLength < EXCEPTION_LENGTH) return;

        // loop and check length-sized buffer chunks
        var maxOffset = bufferLength - EXCEPTION_LENGTH;
        for (var i = 0; i <= maxOffset; i++) {
            var unitId = self._buffer[i];
            var functionCode = self._buffer[i + 1];

            if (unitId !== self._id) continue;

            if (
                functionCode === self._cmd &&
                i + expectedLength <= bufferLength
            ) {
                self._emitData(i, expectedLength);
                return;
            }
            if (
                functionCode === (0x80 | self._cmd) &&
                i + EXCEPTION_LENGTH <= bufferLength
            ) {
                self._emitData(i, EXCEPTION_LENGTH);
                return;
            }

            // frame header matches, but still missing bytes pending
            if (functionCode === (0x7f & self._cmd)) break;
        }
    });

    this._client.on("connect", function() {
        self.openFlag = true;
        handleCallback();
    });

    this._client.on("close", function(had_error) {
        self.openFlag = false;
        handleCallback(had_error);
    });

    this._client.on("error", function(had_error) {
        self.openFlag = false;
        handleCallback(had_error);
    });

    this._client.on("timeout", function() {
        self.openFlag = false;
        modbusSerialDebug("TelnetPort port: TimedOut");
        handleCallback(new Error("TelnetPort Connection Timed Out."));
    });

    /**
     * Check if port is open.
     *
     * @returns {boolean}
     */
    Object.defineProperty(this, "isOpen", {
        enumerable: true,
        get: function() {
            return this.openFlag;
        }
    });

    EventEmitter.call(this);
}
636181
function localhost(local, defaultPort) {
  // edge case when hostname:port is not informed via cli
  if (local === undefined || local === 'true') {
    local = [defaultPort];
  } else {
    local = local.toString().split(':');
  }

  return {
    hostname: reIp.test(local[0]) || isNaN(parseInt(local[0], 10)) &&
      local[0] ? local[0] : os.hostname(),
    port: parseInt(local[1] || (!reIp.test(local[0]) && local[0]), 10) ||
      defaultPort
  };
}
114187
function WebsocketBroker(options) {
  // Superclass Constructor
  EventEmitter.call(this);

  options = options || {};
  this.clientsPath = [];
  this.host = options.host || 'localhost';
  this.port = options.port || 8000;
  this.endpoints = options.endpoints || [];
  this.websocketEndpoints = {};

  this.wsServer = null;
  this.httpServer = null;
}