Represents a redis client connection.

@param socket The underlying socket.
@param options Client connection options.
426233
function Client(socket, options) {
  options = options || {};

  // hook up subcommand nested properties
  var cmd, sub, method;
  for(cmd in SubCommand) {
    // we have defined the cluster slots subcommand
    // but the cluster command is not returned in the
    // command list, ignore this for the moment
    if(!this[cmd]) continue;

    // must re-define the command method
    // so it is not shared across client instances
    method = this[cmd] = this[cmd].bind(this);

    function subcommand(cmd, sub) {
      var args = [].slice.call(arguments, 1), cb;
      if(typeof args[args.length - 1] === 'function') {
        cb = args.pop();
      }
      this.execute(cmd, args, cb);
      return this;
    }


    for(sub in SubCommand[cmd]) {
      method[sub] = subcommand.bind(this, cmd, sub);
    }
  }

  this.socket = socket;
  this.socket.on('connect', this._connect.bind(this));
  this.socket.on('data', this._data.bind(this));
  this.socket.on('error', this._error.bind(this));
  this.socket.on('close', this._close.bind(this));
  this.tcp = (this.socket instanceof Socket);

  // using a tcp socket connection
  if(this.tcp) {
    this.encoder = new Encoder(
      {return_buffers: options.buffers});
    this.encoder.pipe(this.socket);
    this.decoder = new Decoder(
      {
        simple: options.simple,
        return_buffers: options.buffers,
        raw: options.raw
      });
    this.decoder.on('reply', this._reply.bind(this))
  }
}
219670
public void handleConnection(Socket socket)
        throws IOException
    {
        HttpConnection connection = createConnection(socket);
        
        try
        {
            if (_lowResourcePersistTimeMs>0 && isLowOnResources())
            {
                socket.setSoTimeout(_lowResourcePersistTimeMs);
                connection.setThrottled(true);
            }
            else
            {
                socket.setSoTimeout(getMaxIdleTimeMs());
                connection.setThrottled(false);
            }
            
        }
        catch(Exception e)
        {
            log.warn(LogSupport.EXCEPTION,e);
        }

        connection.handle();
    }
1108798
public void connectionComplete(SocketAddress socket)
    {
        assert socket != null;
        activeSocketSessions.remove(socket);
        if (logger.isTraceEnabled())
            logger.trace("ClientState removed for socket addr {}", socket);
    }
1016661
public <T> void setSocketOption(SocketOption<T> socketOption, T value) {
		this.socketOptions.put(socketOption, value);
	}
1362289
public void addConnection(RedisURI redisURI, StatefulRedisConnection<String, String> connection) {

        if (this.closed) { // fastpath
            connection.closeAsync();
            return;
        }

        synchronized (this.connections) {

            if (this.closed) {
                connection.closeAsync();
                return;
            }

            this.connections.put(redisURI, connection);
        }
    }
1316159
function Server(options) {
  options = util._extend({}, options);

  this._log = (options.log || defaultLogger).child({ component: 'http' });
  this._settings = options.settings;

  var start = this._start.bind(this);
  var fallback = this._fallback.bind(this);

  // HTTP2 over TLS (using NPN or ALPN)
  if ((options.key && options.cert) || options.pfx) {
    this._log.info('Creating HTTP/2 server over TLS');
    this._mode = 'tls';
    options.ALPNProtocols = supportedProtocols;
    options.NPNProtocols = supportedProtocols;
    options.ciphers = options.ciphers || cipherSuites;
    options.honorCipherOrder = (options.honorCipherOrder != false);
    this._server = https.createServer(options);
    this._originalSocketListeners = this._server.listeners('secureConnection');
    this._server.removeAllListeners('secureConnection');
    this._server.on('secureConnection', function(socket) {
      var negotiatedProtocol = socket.alpnProtocol || socket.npnProtocol;
      // It's true that the client MUST use SNI, but if it doesn't, we don't care, don't fall back to HTTP/1,
      // since if the ALPN negotiation is otherwise successful, the client thinks we speak HTTP/2 but we don't.
      if (negotiatedProtocol === protocol.VERSION) {
        start(socket);
      } else {
        fallback(socket);
      }
    });
    this._server.on('request', this.emit.bind(this, 'request'));

    forwardEvent('error', this._server, this);
    forwardEvent('listening', this._server, this);
  }

  // HTTP2 over plain TCP
  else if (options.plain) {
    this._log.info('Creating HTTP/2 server over plain TCP');
    this._mode = 'plain';
    this._server = net.createServer(start);
  }

  // HTTP/2 with HTTP/1.1 upgrade
  else {
    this._log.error('Trying to create HTTP/2 server with Upgrade from HTTP/1.1');
    throw new Error('HTTP1.1 -> HTTP2 upgrade is not yet supported. Please provide TLS keys.');
  }

  this._server.on('close', this.emit.bind(this, 'close'));
}
391418
function Client(socket) {

  // flag whether an external or internal client socket
  this._tcp = (socket instanceof Socket);

  // index into the connections array
  this._index = -1;

  // file descriptor
  this._fd = socket._handle.fd;

  // remote ip address
  this._remoteAddress = socket.remoteAddress;

  // remote port
  this._remotePort = socket.remotePort;

  // full remote address
  this._addr =
    (this._remoteAddress && this._remotePort)
      ? this._remoteAddress + ':' + this._remotePort : null;

  // connection id (2^53)
  this._id = ++id;

  // connection name used by setname/getname
  this._name = null;

  // flag used to mark clients as authenticated
  this._authenticated = false;

  // current db for this connection
  this.db = 0;

  // transaction reference for multi blocks
  this._transaction = null;

  // map of keys being watched by this connection
  this._watched = {};

  // monitor slave mode
  this._monitor = false;

  // the timestamp (ms) when this connection was established
  this._connected = Date.now();

  // last command played
  this._cmd = null;

  // buffer for queries
  this._qbuf = new Buffer(0);

  // time when the last command was received, used
  // to get idle time
  this._last = Date.now();

  // encapsulates pubsub state for this client
  this._pubsub = null;
}
1152775
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder,
            RedisURI redisURI) {

        Bootstrap redisBootstrap = new Bootstrap();
        redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
        redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
        redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR);

        SocketOptions socketOptions = getOptions().getSocketOptions();

        redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                Math.toIntExact(socketOptions.getConnectTimeout().toMillis()));

        if (LettuceStrings.isEmpty(redisURI.getSocket())) {
            redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive());
            redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay());
        }

        connectionBuilder.timeout(redisURI.getTimeout());
        connectionBuilder.password(redisURI.getPassword());

        connectionBuilder.bootstrap(redisBootstrap);
        connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
        connectionBuilder.socketAddressSupplier(socketAddressSupplier);
    }
936311
function Socket(/* [options] */) {
    events.EventEmitter.call(this);
    var self = this;

    // Socket
    if (arguments[0] instanceof net.Socket) {
        this._socket = arguments[0];
    } else {
        var options = arguments[0] || {};
        this._socket = new net.Socket(options);
    }
    
    // Configuration
    this.signature = 174021652;

    // Read data
    this._buffers = [];
    this._offset = 0;            // Current offset in the first buffer    
    this._length = 0;            // Sum of all buffers minus offset
    this._messageLength = null;

    // Write data
    this._header = new Buffer(8);
    this._header.writeUInt32BE(this.signature, 0);

    // Event handlers
    this._socket.on('data', this.onData.bind(this));

    // Relay some of the socket events that don't need to be handled
    [   'connect',
        'end',
        'close',
        'timeout',
        'drain',
        'error'
    ].forEach(function (event) {
        self._socket.on(event, function (data) {
            self.emit(event, data);
        });
    });

    // Relay some of the socket properties that don't need to be handled
    [   'remoteAddress',
        'remotePort',
        'bytesRead',
        'bytesWritten',
        'bufferSize'
    ].forEach(function (propertyName) {
        Object.defineProperty(self, propertyName, {
            get: function () {
                return self._socket[propertyName];
            },
            enumerable: true
        });
    });

    // Relay some of the socket functions that don't need to be handled
    [   'connect',
        'destroy',
        'pause',
        'resume',
        'setTimeout',
        'setNoDelay',
        'setKeepAlive',
        'address'
    ].forEach(function (functionName) {
        self[functionName] = function () {
            return self._socket[functionName].apply(self._socket, arguments);
        };
    });
}
844857
function WebsocketRouter(options) {
  options = options || {};
  this.clientsPath = [];
  this.host = options.host ? options.host : 'localhost';
  this.port = options.port ? options.port : 8000;
}
390989
function (options) {
        W.extend(this, W.eventMixin);
        this.socketUrl = options.socketUrl;
        this._connectionDesired = false;
        this.attemptReconnectionAfterMS = (typeof options.attemptReconnectionAfterMS !== 'undefined') ? options.attemptReconnectionAfterMS : 10000;
    }
72491
private function persistentConnect(\stdClass $connectionOptions, $persistentId)
    {
        if (!$this->connection->pconnect(
            $connectionOptions->host,
            $connectionOptions->port,
            $connectionOptions->timeout,
            $persistentId,
            $connectionOptions->retryDelay
        )) {
            throw new RedisConnectionException(
                "Can't connect to redis server with config: " . var_export($connectionOptions, true)
            );
        };
    }
870237
def get_redis(**options):
    
    from uliweb import settings
    from uliweb.utils.common import log
    import redis
        
    options = (options or {})
    options.update(settings.REDIS)
    if 'unix_socket_path' in options:
        client = redis.Redis(unix_socket_path=options['unix_socket_path'])
    else:
        global __connection_pool__
    
        if not __connection_pool__ or __connection_pool__[0] != options['connection_pool']:
            d = {'host':'localhost', 'port':6379}
            d.update(options['connection_pool'])
            __connection_pool__ = (d, redis.ConnectionPool(**d))
        client = redis.Redis(connection_pool=__connection_pool__[1])
        
    if settings.REDIS.test_first:
        try:
            client.info()
        except Exception as e:
            log.exception(e)
            client = None
    return client
710241
def __connect():
    
    global redis_instance
    if use_tcp_socket:
        redis_instance = redis.StrictRedis(host=hostname, port=port)
    else:
        redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)
343068
function ClientChannel(client, opts) {
  opts = opts || {};
  events.EventEmitter.call(this);

  this.client = client;
  this.timeout = utils.getOption(opts, 'timeout', client._timeout$);
  this._endWritable = !!utils.getOption(opts, 'endWritable', true);
  this._prefix = normalizedPrefix(opts.scope);

  var cache = client._cache$;
  var clientSvc = client._svc$;
  var hash = opts.serverHash;
  if (!hash) {
    hash = clientSvc.hash;
  }
  var adapter = cache[hash];
  if (!adapter) {
    // This might happen even if the server hash option was set if the cache
    // doesn't contain the corresponding adapter. In this case we fall back to
    // the client's protocol (as mandated by the spec).
    hash = clientSvc.hash;
    adapter = cache[hash] = new Adapter(clientSvc, clientSvc, hash);
  }
  this._adapter = adapter;

  this._registry = new Registry(this, PREFIX_LENGTH);
  this.pending = 0;
  this.destroyed = false;
  this.draining = false;
  this.once('_eot', function (pending, err) {
    // Since this listener is only run once, we will only forward an error if
    // it is present during the initial `destroy` call, which is OK.
    debug('client channel EOT');
    this.destroyed = true;
    this.emit('eot', pending, err);
  });
}
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)
	});
}
973372
function initRedis(config, callback) {

  var self = this;

  protos.util.checkLocalPort(config.port, function(err) {

    if (err) {
      app.log("RedisTransport [%s:%s] %s", config.host, config.port, err.code);
    } else {

      // Set redis client
      self.client = redis.createClient(config.port, config.host, self.options);

      // Handle error event
      self.client.on('error', function(err) {
        callback.call(self, err);
      });

      // Authenticate if password provided
      if (typeof config.password == 'string') {
        self.client.auth(config.password, function(err, res) {
          if (err) {
            app.log("RedisTransport: [%s:%s] %s", config.host, config.port, err.code);
          } else if (typeof config.db == 'number' && config.db !== 0) {
            self.client.select(config.db, function(err, res) {
              if (err) callback.call(self, err);
              else callback.call(self, null);
            });
          } else {
            callback.call(self, null);
          }
        });
      } else if (typeof config.db == 'number' && config.db !== 0) {
        self.client.select(config.db, function(err, res) {
          callback.call(self, err);
        });
      } else {
        callback.call(self, null);
      }

    }
  });

}