Create a new UDP unicast socket.

@param {dgram.Socket|string|object} socket
@param {object} [options]
@return {Socket}
507832
function createSocket(socket, options = {}) {
  if (!isSocket(socket)) {
    options = socket; // eslint-disable-line no-param-reassign

    if (isSocket(options.socket)) {
      // eslint-disable-next-line no-param-reassign, prefer-destructuring
      socket = options.socket;
    } else {
      socket = dgram.createSocket(options); // eslint-disable-line no-param-reassign
      socket.bind(options.port || 0, options.address || '0.0.0.0');
    }
  }

  return new Socket(Object.assign({}, options, { socket }));
}
367961
function(socket) {
    // Make note of the port numbers for any identd lookups
    // Nodejs < 0.9.6 has no socket.localPort so check this first
    if (typeof socket.localPort !== 'undefined') {
        this.identd_port_pair = socket.localPort.toString() + '_' + socket.remotePort.toString();
        global.clients.port_pairs[this.identd_port_pair] = this;
    }
}
731832
def create_socket():
    
    sock = socket.socket(PF_CAN, socket.SOCK_RAW, CAN_RAW)

    log.info('Created a socket')

    return sock
226064
function Server(opts){
  // Shorthand, no "new" required.
  if (!(this instanceof Server))
    return new Server(...arguments);

  if (typeof opts !== 'object')
    opts = {};

  this.clients = opts.dummies || [];

  this.server = opts.server || new SocketServer(socket => {
    let client = new Client(socket);
    this.clients.push(client);
    this.emit('connection', client);

    client._socket.once('data', handshake.bind(client));
    client.on('handshake-done', () => {
      client._socket.on('data', message.bind(client));
    });
  });
}
636249
protected function createSocket($type, $mode, $dsn = null, $options = array())
    {
        $context = $this->getContext();
        $socket = new Socket($context, $type);

        $options = $this->options + $options;
        foreach ($options as $key => $value) {
            $socket->setSockOpt($key, $value);
        }

        $this->connect($socket, $mode, $dsn);

        return $socket;
    }
1188621
function Socket(sio, options) {
  if (!(this instanceof Socket)) {
    return new Socket(sio, options);
  }

  EventEmitter.call(this);

  options = options || {};

  this.sio = sio;
  this.forceBase64 = !!options.forceBase64;
  this.streams = {};
  this.encoder = new parser.Encoder();
  this.decoder = new parser.Decoder();

  var eventName = exports.event;
  sio.on(eventName, bind(this, emit));
  sio.on(eventName + '-read', bind(this, '_onread'));
  sio.on(eventName + '-write', bind(this, '_onwrite'));
  sio.on(eventName + '-end', bind(this, '_onend'));
  sio.on(eventName + '-error', bind(this, '_onerror'));
  sio.on('error', bind(this, emit, 'error'));
  sio.on('disconnect', bind(this, '_ondisconnect'));

  this.encoder.on('stream', bind(this, '_onencode'));
  this.decoder.on('stream', bind(this, '_ondecode'));
}
385520
function createSocket(type, receive)
{
  try{ // newer
    var sock = dgram.createSocket({ type: type, reuseAddr: true }, receive);
  }catch(E){ // older
    var sock = dgram.createSocket(type, receive);
  }
  return sock;
}
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));
    });
}
334492
function SocketPeer (opts) {
  var self = this;

  if (!(self instanceof SocketPeer)) {
    return new SocketPeer(opts);
  }

  opts = opts || {};

  EventEmitter.call(self);

  self._connections = {
    socket: {success: 0, error: 0, attempt: 0},
    rtc: {success: 0, error: 0, attempt: 0}
  };
  self.peer = null;
  self.rtcConnected = false;
  self.socketConnected = false;

  extend(self, {
    pairCode: 'pairCode' in opts ? opts.pairCode : null,
    socketFallback: 'socketFallback' in opts ? opts.socketFallback : true,
    socket: 'socket' in opts ? opts.socket : null,
    stream: 'stream' in opts ? opts.stream : null,
    url: 'url' in opts ? opts.url : 'http://localhost',
    reconnect: 'reconnect' in opts ? opts.reconnect : true,
    reconnectDelay: 'reconnectDelay' in opts ? opts.reconnectDelay : 1000,
    timeout: 'timeout' in opts ? opts.timeout : 0,
    autoconnect: 'autoconnect' in opts ? opts.autoconnect : true,
    debug: 'debug' in opts ? opts.debug : false
  }, opts);

  self._debug('New peer');

  self.on('peer.found', function (data) {
    self.socketConnected = true;
    clearTimeout(self._socketConnectTimeout);
    clearTimeout(self._socketReconnectDelayTimeout);
    self._connections.socket.attempt = 0;
    self._connections.socket.success++;

    self.emit('connect');
    if (self._connections.socket.success > 0) {
      self.emit('reconnect');
    }

    self.initiator = data.initiator;

    if (data.initiator) {
      self._send('rtc.connect');
      self._rtcInit();
    }
  });
  self.on('rtc.signal', self._rtcSignal);
  self.on('rtc.connect', function () {
    self._rtcInit();
  });

  self.on('busy', function () {
    self._socketError(new Error('Pair code "' + self.pairCode + '" already in use'));
    self.socket.close();
  });

  if (self.autoconnect) {
    setTimeout(function () {
      self.connect();
    }, 0);
  }
}
891292
function SocketServices( options ){
	options = options || {};

	var self = this;

	this.logger = Logger.createLogger( 'socket', {'socket-services': VERSION}, options.logger );

	self.server = options.server || { };

	this.messageValidator = options.messageValidator || isCommunication;

	this.channel = options.channel || 'api';
	this.event = options.event || 'rester';

	self.logger.info('Will accepting communication on channel \'' + self.channel + '\' emitting to event \'' + self.event + '\'' );

	this.inflicter = new Inflicter( { logger: self.logger, idLength: options.idLength || 16 } );

	self.logger.info( 'Event system activated.' );
}
420021
function WebsocketConnection(socket, url) {
  this.socket = socket;
  this.url = url;

  this.deferreds = {};
  this.nextRequestId = 0;

  this.onReply = this.onReply.bind(this);
  this.onEvent = this.onEvent.bind(this);
}
163670
function(ip, options) {
    var modbus = this;
    this.ip = ip;
    this.openFlag = false;

    // options
    if (typeof(options) === "undefined") options = {};
    this.port = options.port || C701_PORT; // C701 port

    // create a socket
    this._client = dgram.createSocket("udp4");

    // wait for answer
    this._client.on("message", function(data) {
        var buffer = null;

        // check expected length
        if (modbus.length < 6) return;

        // check message length
        if (data.length < (116 + 5)) return;

        // check the C701 packet magic
        if (data.readUInt16LE(2) !== 602) return;

        // check for modbus valid answer
        // get the serial data from the C701 packet
        buffer = data.slice(data.length - modbus._length);

        modbusSerialDebug({ action: "receive c701 upd port", data: data, buffer: buffer });
        modbusSerialDebug(JSON.stringify({ action: "receive c701 upd port strings", data: data, buffer: buffer }));

        // check the serial data
        if (_checkData(modbus, buffer)) {
            modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
            modbusSerialDebug(JSON.stringify({ action: "emit data serial rtu buffered port strings", buffer: buffer }));

            modbus.emit("data", buffer);
        } else {
            // check for modbus exception
            // get the serial data from the C701 packet
            buffer = data.slice(data.length - 5);

            // check the serial data
            if (_checkData(modbus, buffer)) {
                modbusSerialDebug({ action: "emit data serial rtu buffered port", buffer: buffer });
                modbusSerialDebug(JSON.stringify({
                    action: "emit data serial rtu buffered port strings",
                    buffer: buffer
                }));

                modbus.emit("data", buffer);
            }
        }
    });

    this._client.on("listening", function() {
        modbus.openFlag = true;
    });

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

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

    EventEmitter.call(this);
}
44899
function WalletClient(options) {
  if (!(this instanceof WalletClient))
    return new WalletClient(options);

  if (!options)
    options = {};

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

  AsyncObject.call(this);

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

  this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
  this.apiKey = options.apiKey;

  this.socket = null;
}
867371
function adapter(uri, opts) {
  opts = opts || {};

  // handle options only
  if ('object' == typeof uri) {
    opts = uri;
    uri = null;
  }

  // opts
  var pub = opts.pubClient;
  var sub = opts.subClient;
  var prefix = opts.key || 'socket.io';
  var requestsTimeout = opts.requestsTimeout || 5000;

  // init clients if needed
  function createClient() {
    if (uri) {
      // handle uri string
      return redis(uri, opts);
    } else {
      return redis(opts);
    }
  }

  if (!pub) pub = createClient();
  if (!sub) sub = createClient();

  // this server's key
  var uid = uid2(6);

  /**
   * Adapter constructor.
   *
   * @param {String} namespace name
   * @api public
   */

  function Redis(nsp){
    Adapter.call(this, nsp);

    this.uid = uid;
    this.prefix = prefix;
    this.requestsTimeout = requestsTimeout;

    this.channel = prefix + '#' + nsp.name + '#';
    this.requestChannel = prefix + '-request#' + this.nsp.name + '#';
    this.responseChannel = prefix + '-response#' + this.nsp.name + '#';
    this.requests = {};
    this.customHook = function(data, cb){ cb(null); }

    if (String.prototype.startsWith) {
      this.channelMatches = function (messageChannel, subscribedChannel) {
        return messageChannel.startsWith(subscribedChannel);
      }
    } else { // Fallback to other impl for older Node.js
      this.channelMatches = function (messageChannel, subscribedChannel) {
        return messageChannel.substr(0, subscribedChannel.length) === subscribedChannel;
      }
    }
    this.pubClient = pub;
    this.subClient = sub;

    var self = this;

    sub.psubscribe(this.channel + '*', function(err){
      if (err) self.emit('error', err);
    });

    sub.on('pmessageBuffer', this.onmessage.bind(this));

    sub.subscribe([this.requestChannel, this.responseChannel], function(err){
      if (err) self.emit('error', err);
    });

    sub.on('messageBuffer', this.onrequest.bind(this));

    function onError(err) {
      self.emit('error', err);
    }
    pub.on('error', onError);
    sub.on('error', onError);
  }

  /**
   * Inherits from `Adapter`.
   */

  Redis.prototype.__proto__ = Adapter.prototype;

  /**
   * Called with a subscription message
   *
   * @api private
   */

  Redis.prototype.onmessage = function(pattern, channel, msg){
    channel = channel.toString();

    if (!this.channelMatches(channel, this.channel)) {
      return debug('ignore different channel');
    }

    var room = channel.slice(this.channel.length, -1);
    if (room !== '' && !this.rooms.hasOwnProperty(room)) {
      return debug('ignore unknown room %s', room);
    }

    var args = msgpack.decode(msg);
    var packet;

    if (uid === args.shift()) return debug('ignore same uid');

    packet = args[0];

    if (packet && packet.nsp === undefined) {
      packet.nsp = '/';
    }

    if (!packet || packet.nsp != this.nsp.name) {
      return debug('ignore different namespace');
    }

    args.push(true);

    this.broadcast.apply(this, args);
  };

  /**
   * Called on request from another node
   *
   * @api private
   */

  Redis.prototype.onrequest = function(channel, msg){
    channel = channel.toString();

    if (this.channelMatches(channel, this.responseChannel)) {
      return this.onresponse(channel, msg);
    } else if (!this.channelMatches(channel, this.requestChannel)) {
      return debug('ignore different channel');
    }

    var self = this;
    var request;

    try {
      request = JSON.parse(msg);
    } catch(err){
      self.emit('error', err);
      return;
    }

    debug('received request %j', request);

    switch (request.type) {

      case requestTypes.clients:
        Adapter.prototype.clients.call(self, request.rooms, function(err, clients){
          if(err){
            self.emit('error', err);
            return;
          }

          var response = JSON.stringify({
            requestid: request.requestid,
            clients: clients
          });

          pub.publish(self.responseChannel, response);
        });
        break;

      case requestTypes.clientRooms:
        Adapter.prototype.clientRooms.call(self, request.sid, function(err, rooms){
          if(err){
            self.emit('error', err);
            return;
          }

          if (!rooms) { return; }

          var response = JSON.stringify({
            requestid: request.requestid,
            rooms: rooms
          });

          pub.publish(self.responseChannel, response);
        });
        break;

      case requestTypes.allRooms:

        var response = JSON.stringify({
          requestid: request.requestid,
          rooms: Object.keys(this.rooms)
        });

        pub.publish(self.responseChannel, response);
        break;

      case requestTypes.remoteJoin:

        var socket = this.nsp.connected[request.sid];
        if (!socket) { return; }

        socket.join(request.room, function(){
          var response = JSON.stringify({
            requestid: request.requestid
          });

          pub.publish(self.responseChannel, response);
        });
        break;

      case requestTypes.remoteLeave:

        var socket = this.nsp.connected[request.sid];
        if (!socket) { return; }

        socket.leave(request.room, function(){
          var response = JSON.stringify({
            requestid: request.requestid
          });

          pub.publish(self.responseChannel, response);
        });
        break;

      case requestTypes.remoteDisconnect:

        var socket = this.nsp.connected[request.sid];
        if (!socket) { return; }

        socket.disconnect(request.close);

        var response = JSON.stringify({
          requestid: request.requestid
        });

        pub.publish(self.responseChannel, response);
        break;

      case requestTypes.customRequest:
        this.customHook(request.data, function(data) {

          var response = JSON.stringify({
            requestid: request.requestid,
            data: data
          });

          pub.publish(self.responseChannel, response);
        });

        break;

      default:
        debug('ignoring unknown request type: %s', request.type);
    }
  };

  /**
   * Called on response from another node
   *
   * @api private
   */

  Redis.prototype.onresponse = function(channel, msg){
    var self = this;
    var response;

    try {
      response = JSON.parse(msg);
    } catch(err){
      self.emit('error', err);
      return;
    }

    var requestid = response.requestid;

    if (!requestid || !self.requests[requestid]) {
      debug('ignoring unknown request');
      return;
    }

    debug('received response %j', response);

    var request = self.requests[requestid];

    switch (request.type) {

      case requestTypes.clients:
        request.msgCount++;

        // ignore if response does not contain 'clients' key
        if(!response.clients || !Array.isArray(response.clients)) return;

        for(var i = 0; i < response.clients.length; i++){
          request.clients[response.clients[i]] = true;
        }

        if (request.msgCount === request.numsub) {
          clearTimeout(request.timeout);
          if (request.callback) process.nextTick(request.callback.bind(null, null, Object.keys(request.clients)));
          delete self.requests[requestid];
        }
        break;

      case requestTypes.clientRooms:
        clearTimeout(request.timeout);
        if (request.callback) process.nextTick(request.callback.bind(null, null, response.rooms));
        delete self.requests[requestid];
        break;

      case requestTypes.allRooms:
        request.msgCount++;

        // ignore if response does not contain 'rooms' key
        if(!response.rooms || !Array.isArray(response.rooms)) return;

        for(var i = 0; i < response.rooms.length; i++){
          request.rooms[response.rooms[i]] = true;
        }

        if (request.msgCount === request.numsub) {
          clearTimeout(request.timeout);
          if (request.callback) process.nextTick(request.callback.bind(null, null, Object.keys(request.rooms)));
          delete self.requests[requestid];
        }
        break;

      case requestTypes.remoteJoin:
      case requestTypes.remoteLeave:
      case requestTypes.remoteDisconnect:
        clearTimeout(request.timeout);
        if (request.callback) process.nextTick(request.callback.bind(null, null));
        delete self.requests[requestid];
        break;

      case requestTypes.customRequest:
        request.msgCount++;

        request.replies.push(response.data);

        if (request.msgCount === request.numsub) {
          clearTimeout(request.timeout);
          if (request.callback) process.nextTick(request.callback.bind(null, null, request.replies));
          delete self.requests[requestid];
        }
        break;

      default:
        debug('ignoring unknown request type: %s', request.type);
    }
  };

  /**
   * Broadcasts a packet.
   *
   * @param {Object} packet to emit
   * @param {Object} options
   * @param {Boolean} whether the packet came from another node
   * @api public
   */

  Redis.prototype.broadcast = function(packet, opts, remote){
    packet.nsp = this.nsp.name;
    if (!(remote || (opts && opts.flags && opts.flags.local))) {
      var msg = msgpack.encode([uid, packet, opts]);
      var channel = this.channel;
      if (opts.rooms && opts.rooms.length === 1) {
        channel += opts.rooms[0] + '#';
      }
      debug('publishing message to channel %s', channel);
      pub.publish(channel, msg);
    }
    Adapter.prototype.broadcast.call(this, packet, opts);
  };

  /**
   * Gets a list of clients by sid.
   *
   * @param {Array} explicit set of rooms to check.
   * @param {Function} callback
   * @api public
   */

  Redis.prototype.clients = function(rooms, fn){
    if ('function' == typeof rooms){
      fn = rooms;
      rooms = null;
    }

    rooms = rooms || [];

    var self = this;
    var requestid = uid2(6);

    pub.send_command('pubsub', ['numsub', self.requestChannel], function(err, numsub){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }

      numsub = parseInt(numsub[1], 10);
      debug('waiting for %d responses to "clients" request', numsub);

      var request = JSON.stringify({
        requestid : requestid,
        type: requestTypes.clients,
        rooms : rooms
      });

      // if there is no response for x second, return result
      var timeout = setTimeout(function() {
        var request = self.requests[requestid];
        if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for clients response'), Object.keys(request.clients)));
        delete self.requests[requestid];
      }, self.requestsTimeout);

      self.requests[requestid] = {
        type: requestTypes.clients,
        numsub: numsub,
        msgCount: 0,
        clients: {},
        callback: fn,
        timeout: timeout
      };

      pub.publish(self.requestChannel, request);
    });
  };

  /**
   * Gets the list of rooms a given client has joined.
   *
   * @param {String} client id
   * @param {Function} callback
   * @api public
   */

  Redis.prototype.clientRooms = function(id, fn){

    var self = this;
    var requestid = uid2(6);

    var rooms = this.sids[id];

    if (rooms) {
      if (fn) process.nextTick(fn.bind(null, null, Object.keys(rooms)));
      return;
    }

    var request = JSON.stringify({
      requestid : requestid,
      type: requestTypes.clientRooms,
      sid : id
    });

    // if there is no response for x second, return result
    var timeout = setTimeout(function() {
      if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for rooms response')));
      delete self.requests[requestid];
    }, self.requestsTimeout);

    self.requests[requestid] = {
      type: requestTypes.clientRooms,
      callback: fn,
      timeout: timeout
    };

    pub.publish(self.requestChannel, request);
  };

  /**
   * Gets the list of all rooms (accross every node)
   *
   * @param {Function} callback
   * @api public
   */

  Redis.prototype.allRooms = function(fn){

    var self = this;
    var requestid = uid2(6);

    pub.send_command('pubsub', ['numsub', self.requestChannel], function(err, numsub){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }

      numsub = parseInt(numsub[1], 10);
      debug('waiting for %d responses to "allRooms" request', numsub);

      var request = JSON.stringify({
        requestid : requestid,
        type: requestTypes.allRooms
      });

      // if there is no response for x second, return result
      var timeout = setTimeout(function() {
        var request = self.requests[requestid];
        if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for allRooms response'), Object.keys(request.rooms)));
        delete self.requests[requestid];
      }, self.requestsTimeout);

      self.requests[requestid] = {
        type: requestTypes.allRooms,
        numsub: numsub,
        msgCount: 0,
        rooms: {},
        callback: fn,
        timeout: timeout
      };

      pub.publish(self.requestChannel, request);
    });
  };

  /**
   * Makes the socket with the given id join the room
   *
   * @param {String} socket id
   * @param {String} room name
   * @param {Function} callback
   * @api public
   */

  Redis.prototype.remoteJoin = function(id, room, fn){

    var self = this;
    var requestid = uid2(6);

    var socket = this.nsp.connected[id];
    if (socket) {
      socket.join(room, fn);
      return;
    }

    var request = JSON.stringify({
      requestid : requestid,
      type: requestTypes.remoteJoin,
      sid: id,
      room: room
    });

    // if there is no response for x second, return result
    var timeout = setTimeout(function() {
      if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for remoteJoin response')));
      delete self.requests[requestid];
    }, self.requestsTimeout);

    self.requests[requestid] = {
      type: requestTypes.remoteJoin,
      callback: fn,
      timeout: timeout
    };

    pub.publish(self.requestChannel, request);
  };

  /**
   * Makes the socket with the given id leave the room
   *
   * @param {String} socket id
   * @param {String} room name
   * @param {Function} callback
   * @api public
   */

  Redis.prototype.remoteLeave = function(id, room, fn){

    var self = this;
    var requestid = uid2(6);

    var socket = this.nsp.connected[id];
    if (socket) {
      socket.leave(room, fn);
      return;
    }

    var request = JSON.stringify({
      requestid : requestid,
      type: requestTypes.remoteLeave,
      sid: id,
      room: room
    });

    // if there is no response for x second, return result
    var timeout = setTimeout(function() {
      if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for remoteLeave response')));
      delete self.requests[requestid];
    }, self.requestsTimeout);

    self.requests[requestid] = {
      type: requestTypes.remoteLeave,
      callback: fn,
      timeout: timeout
    };

    pub.publish(self.requestChannel, request);
  };

  /**
   * Makes the socket with the given id to be disconnected forcefully
   * @param {String} socket id
   * @param {Boolean} close if `true`, closes the underlying connection
   * @param {Function} callback
   */

  Redis.prototype.remoteDisconnect = function(id, close, fn) {
    var self = this;
    var requestid = uid2(6);

    var socket = this.nsp.connected[id];
    if(socket) {
      socket.disconnect(close);
      if (fn) process.nextTick(fn.bind(null, null));
      return;
    }

    var request = JSON.stringify({
      requestid : requestid,
      type: requestTypes.remoteDisconnect,
      sid: id,
      close: close
    });

    // if there is no response for x second, return result
    var timeout = setTimeout(function() {
      if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for remoteDisconnect response')));
      delete self.requests[requestid];
    }, self.requestsTimeout);

    self.requests[requestid] = {
      type: requestTypes.remoteDisconnect,
      callback: fn,
      timeout: timeout
    };

    pub.publish(self.requestChannel, request);
  };

  /**
   * Sends a new custom request to other nodes
   *
   * @param {Object} data (no binary)
   * @param {Function} callback
   * @api public
   */

  Redis.prototype.customRequest = function(data, fn){
    if (typeof data === 'function'){
      fn = data;
      data = null;
    }

    var self = this;
    var requestid = uid2(6);

    pub.send_command('pubsub', ['numsub', self.requestChannel], function(err, numsub){
      if (err) {
        self.emit('error', err);
        if (fn) fn(err);
        return;
      }

      numsub = parseInt(numsub[1], 10);
      debug('waiting for %d responses to "customRequest" request', numsub);

      var request = JSON.stringify({
        requestid : requestid,
        type: requestTypes.customRequest,
        data: data
      });

      // if there is no response for x second, return result
      var timeout = setTimeout(function() {
        var request = self.requests[requestid];
        if (fn) process.nextTick(fn.bind(null, new Error('timeout reached while waiting for customRequest response'), request.replies));
        delete self.requests[requestid];
      }, self.requestsTimeout);

      self.requests[requestid] = {
        type: requestTypes.customRequest,
        numsub: numsub,
        msgCount: 0,
        replies: [],
        callback: fn,
        timeout: timeout
      };

      pub.publish(self.requestChannel, request);
    });
  };

  Redis.uid = uid;
  Redis.pubClient = pub;
  Redis.subClient = sub;
  Redis.prefix = prefix;
  Redis.requestsTimeout = requestsTimeout;

  return Redis;

}
849678
function (options) {

      var clientShell = this,
      context = {},
      // Default settings.
      defaultSettings = {
        namespace: 'shotgun',
        debug: false
      };

      // Override default settings with supplied options.
      var settings = clientShell.settings = extend(true, {}, defaultSettings, options);

      // Instruct socket.io to connect to the server.
      var socket = clientShell.socket = io.connect('/' + settings.namespace);

      // Proxy any listeners onto the socket itself.
      clientShell.on = function () {
        socket.on.apply(socket, arguments);
        return clientShell;
      };

      // Proxy any emit calls onto the socket itself.
      clientShell.emit = function () {
        socket.emit.apply(socket, arguments);
        return clientShell;
      };

      function getCookies() {
        var cookies = {};
        if (document.cookie.length > 0)
          document.cookie.split(';').forEach(function (cookie) {
            var components = cookie.split('='),
            name = components[0].trim(),
            value = components[1];
            if (name.indexOf(settings.namespace + '-') === 0) {
              name = name.replace(settings.namespace + '-', '');
              cookies[name] = decodeURIComponent(value);
            }
          });
          return cookies;
      }

      clientShell
      // Save context when it changes.
      .on('contextChanged', function (contextData) {
        context = contextData;
      })
      // Create a function for setting cookies in the browser.
      .on('setCookie', function (name, value, days) {
        var expiration = new Date();
        expiration.setDate(expiration.getDate() + days);
        value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString());
        document.cookie = settings.namespace + '-' + name + "=" + value;
      })
      .on('getCookie', function (name, callback) {
        // Create a cookies property on the context and fill it with all the cookies for this shell.
        var cookies = getCookies();
        callback(cookies[name]);
      })
      .on('getAllCookies', function (callback) {
        var cookies = getCookies();
        callback(cookies);
      });

      // Create an execute function that looks similar to the shotgun shell execute function for ease of use.
      clientShell.execute = function (cmdStr, contextOverride, options) {
        // If a context was passed in then override the stored context with it.
        if (contextOverride) context = contextOverride;
        socket.emit('execute', cmdStr, context, options);
        return clientShell;
      };

      return clientShell;
    }
165561
function init(options){
	options = util._extend({ssl:null, port:12345}, options);
	var serverWorkers = {}; // save main server sockets
	var clientSocket = []; // save local server socket
	var clientOptions = []; // save optioin obj
	var wsServer;
	if(options.ssl)
		wsServer = require('https').createServer(options.ssl);
	else wsServer = require('http').createServer();
	var io = require('socket.io')(wsServer);
	
	if(options.auth)	
	io.set('authorization', function (handshakeData, callback) {
		if(handshakeData.url.match('username='+options.auth.username+'&password='+options.auth.password))
        	callback(null, true); // error first callback style 
        else callback('no auth', false);
    });

	io.on('connection', function(socket){
		// 0. save server sockets & local socket
		socket.on('init', function(data){
			if(data._type == 'localServer'){
				socket._type = 'localServer';
				if(clientSocket.length>0)
					clientSocket.slice(-1)[0].emit('hold');			
				// then handle new one
				clientSocket.push(socket);
				clientOptions.push(data);
				// inform server the new client
				for(i in serverWorkers)
					serverWorkers[i].emit('client', data);
			}else if(data._type == 'server'){
				socket._type = 'server';
				serverWorkers[socket.id] = socket;
			}else{
				// ignore this connection
			}
		})
		// handle req from server, relay data to client
		socket.on('req', function(data){
			if(clientSocket.length > 0){
				data._sid = socket.id;
				clientSocket.slice(-1)[0].emit('req', data)
			}
		})
		// handle res from client, relay the data to the server
		socket.on('res', function(data){
			if(serverWorkers[data._sid])
				serverWorkers[data._sid].emit('res', data);
		});
		socket.on('disconnect', function(reason){
			if(socket._type == 'localServer'){
				var last = false;
				for(i in clientSocket){
					if(socket.id == clientSocket[i].id){
						if(i == clientSocket.length-1)
							last = true;
						clientSocket.splice(i, 1);
						clientOptions.splice(i,1);
						break;
					}
				}
				if(clientSocket.length > 0 && clientOptions.length > 0){
					if(last)
						clientSocket.slice(-1)[0].emit('back');	
					for(i in serverWorkers)
						serverWorkers[i].emit('client', clientOptions.slice(-1)[0]);
				}
				else
					for(i in serverWorkers)
						serverWorkers[i].emit('client', false);
			}
			else if(socket._type == 'server')
				delete serverWorkers[socket.id];
		});
	});
	wsServer.listen(options.port).on('listening', function(){
		options.listening ? options.listening() : noop();
		//console.log('[NLT] Server is ready on port ' + options.port);
	}).on('error', function(e){
		options.error ? options.error(e) : noop();
		//console.log('[NLT] Setup error', e)
	});
}
1096702
def create_local_socket (self):
        """"""
        sock = create_socket(socket.AF_UNIX, socket.SOCK_STREAM)
        addr = self['LocalSocket']
        try:
            sock.connect(addr)
        except socket.error:
            sock.close()
            raise
        return sock