add new socket handle by url

@private
@param	{object}	oSocket
@returns {boolean}
483820
function _cacheAddHandle( oSocket )
{
	if ( ! oSocket )
	{
		return false;
	}

	//	...
	_cacheRemoveHandle( oSocket );
	m_arrCacheOutboundPeers.push( oSocket );
	return true;
}
1371061
@Override
	public Socket createSocket(String host, int port) throws IOException,
			UnknownHostException {
		long start = System.currentTimeMillis();
		InetAddress addr = InetAddress.getByName(host);
		long end = System.currentTimeMillis();
		PerformanceLogger.noteElapsed("DNS:" + host, end - start);
		return new Socket(addr, port);
	}
423606
function Router(socket, options) {
  stream.Transform.call(this, { objectMode: true });

  this.options = merge(Object.create(Router.DEFAULTS), options || {});
  this.socket = socket;
}
1016625
function serveClientOnExpressRoute(app) {


  app.get("/myelements/myelements.jquery.js", function(req, res) {
    //logic taken form socket.io's serveClient
    // var etag = req.headers['if-none-match'];
    // if (etag) {
    //   if (clientVersion == etag) {
    //     debug('serve client 304');
    //     res.writeHead(304);
    //     res.end();
    //     return;
    //   }
    // }
    // debug('serve client source');
    // res.setHeader('ETag', clientVersion);
    res.setHeader("Content-type", "application/javascript");
    var result = Server.client();

    res.send(result);
    //res.sendFile(path.join(__dirname, "client.js"));
  });
}
303527
public boolean accept(SocketBar qSocket)
    throws IOException
  {
    SocketChannelWrapperBar s = (SocketChannelWrapperBar) qSocket;

    //Socket socket = _ss.accept();
    
    SocketChannel socket = _ss.accept();
    
    if (socket == null) {
      return false;
    }

    s.init(socket);

    /*
    // XXX:
    if (isTcpNoDelay())
      socket.setTcpNoDelay(true);
    
    if (isTcpKeepalive())
      socket.setKeepAlive(true);

    if (_connectionSocketTimeout > 0)
      socket.setSoTimeout(_connectionSocketTimeout);

    s.init(socket);
    */

    if (_connectionSocketTimeout > 0) {
      // XXX: socket.setSoTimeout(_connectionSocketTimeout);
    }
    
    return true;
  }
1084531
function exportSocket(exports, beyond, host) {
        "use strict";
    
        if (beyond.params.local && host.substr(0, 1) === '/') {
            host = location.hostname + ':' + beyond.hosts.ports.ws + host;
        }
    
        var io, socket;
    
        var callbacks = [];
        exports.socket = function (callback) {
    
            if (socket) {
                callback(socket);
                return;
            }
    
            callbacks.push(callback);
    
        };
    
        function createSocket() {
    
            var query = beyond.sockets.getConnectionParams(host);
            var qstring = '';
            for (var variable in query) {
                if (qstring) qstring += '&';
                qstring += variable + '=' + query[variable];
            }
    
            socket = io.connect(host, {'query': qstring, 'reconnection': false});
    
            for (var i in callbacks) callbacks[i](socket);
            callbacks = [];
    
        }
    
        require(['socket.io'], function (_io) {
            io = _io;
            createSocket();
        });
    
    }
776871
function initialiseSocket(socket, callback) {
    var request = socket.request,
        address = request.meta.remote_address,
        revdns;

    // Key/val data stored to the socket to be read later on
    // May also be synced to a redis DB to lookup clients
    socket.meta = socket.request.meta;

    // If a forwarded-for header is found, switch the source address
    if (request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for']) {
        // Check we're connecting from a whitelisted proxy
        if (!global.config.http_proxies || !rangeCheck(address, global.config.http_proxies)) {
            winston.info('Unlisted proxy: %s', address);
            callback(null, false);
            return;
        }

        // We're sent from a whitelisted proxy, replace the hosts
        address = request.headers[global.config.http_proxy_ip_header || 'x-forwarded-for'];

        // Multiple reverse proxies will have a comma delimited list of IPs. We only need the first
        address = address.split(',')[0].trim();

        // Some reverse proxies (IIS) may include the port, so lets remove that (if ipv4)
        if (address.indexOf('.') > -1) {
            address = (address || '').split(':')[0];
        }
    }

    socket.meta.real_address = address;

    // If enabled, don't go over the connection limit
    if (global.config.max_client_conns && global.config.max_client_conns > 0) {
        if (global.clients.numOnAddress(address) + 1 > global.config.max_client_conns) {
            return callback(null, false);
        }
    }


    try {
        dns.reverse(address, function (err, domains) {
            if (!err && domains.length > 0) {
                revdns = _.first(domains);
            }

            if (!revdns) {
                // No reverse DNS found, use the IP
                socket.meta.revdns = address;
                callback(null, true);

            } else {
                // Make sure the reverse DNS matches the A record to use the hostname..
                dns.lookup(revdns, function (err, ip_address, family) {
                    if (!err && ip_address == address) {
                        // A record matches PTR, perfectly valid hostname
                        socket.meta.revdns = revdns;
                    } else {
                        // A record does not match the PTR, invalid hostname
                        socket.meta.revdns = address;
                    }

                    // We have all the info we need, proceed with the connection
                    callback(null, true);
                });
            }
        });

    } catch (err) {
        socket.meta.revdns = address;
        callback(null, true);
    }
}
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;
}
303886
function() {
		    //io = socket(process.env.PORT || process.env.NODE_PORT || 3333);
        io = socket(http);

		    io.on('connection', function(socket){
            console.log('connection happened');
			      //Logic for handeling a new connection here.
			      //ie. registering a user or something similar.

			      //The new connection can send commands.
			      socket.on('keydown', function(data) {
				        var index = keysToPress.indexOf(data.key);
				        if(index === -1) {
					          keysToPress.push(data.key);
				        }
			      });

			      socket.on('keyup', function(data) {
				        var index = keysToPress.indexOf(data.key);
				        if(index !== -1) {
					          keysToPress.splice(index, 1);
				        }
			      });

			      socket.on('restart', function(data) {
				        gameboy_instance.loadROM(rom);
			      });

		    });
	  }
868202
function socketClient(serviceUrl) {
  var self = object.create(socketClient.prototype);
  var urlObject = url.parse(serviceUrl);

  // create the url without the path
  var socketIoUrl = url.format({
    protocol: urlObject.protocol,
    hostname: urlObject.hostname
  });

  var options = {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 50000,
    reconnectionAttempts: 5,
    autoConnect: false,
    path: url.clearTraliningSlash(urlObject.path) + '/socket.io/'
  };

  self.socket = io(socketIoUrl, options);
  self.opened = false;

  return self;
}
1099280
function connect(options, connectListener)
{
	var socket = net.connect(options, () => {
		if ( connectListener )
		{
			connectListener();
		}
	});
	
	return new Client(socket, options);
}
516066
public void addServerSocket(
      InternalInstrumented<ServerStats> server, InternalInstrumented<SocketStats> socket) {
    ServerSocketMap serverSockets = perServerSockets.get(id(server));
    assert serverSockets != null;
    add(serverSockets, socket);
  }
94903
function connect (req, opts, fn) {

  var proxy = this.proxy;

  // create a socket connection to the proxy server
  var socket;
  if (this.secureProxy) {
    socket = tls.connect(proxy);
  } else {
    socket = net.connect(proxy);
  }

  // we need to buffer any HTTP traffic that happens with the proxy before we get
  // the CONNECT response, so that if the response is anything other than an "200"
  // response code, then we can re-play the "data" events on the socket once the
  // HTTP parser is hooked up...
  var buffers = [];
  var buffersLength = 0;

  function read () {
    var b = socket.read();
    if (b) ondata(b);
    else socket.once('readable', read);
  }

  function cleanup () {
    socket.removeListener('data', ondata);
    socket.removeListener('end', onend);
    socket.removeListener('error', onerror);
    socket.removeListener('close', onclose);
    socket.removeListener('readable', read);
  }

  function onclose (err) {
    debug('onclose had error %o', err);
  }

  function onend () {
    debug('onend');
  }

  function onerror (err) {
    cleanup();
    fn(err);
  }

  function ondata (b) {
    buffers.push(b);
    buffersLength += b.length;
    var buffered = Buffer.concat(buffers, buffersLength);
    var str = buffered.toString('ascii');

    if (!~str.indexOf('\r\n\r\n')) {
      // keep buffering
      debug('have not received end of HTTP headers yet...');
      if (socket.read) {
        read();
      } else {
        socket.once('data', ondata);
      }
      return;
    }

    var firstLine = str.substring(0, str.indexOf('\r\n'));
    var statusCode = +firstLine.split(' ')[1];
    debug('got proxy server response: %o', firstLine);

    if (200 == statusCode) {
      // 200 Connected status code!
      var sock = socket;

      // nullify the buffered data since we won't be needing it
      buffers = buffered = null;

      if (opts.secureEndpoint) {
        var host = opts.host;
        // since the proxy is connecting to an SSL server, we have
        // to upgrade this socket connection to an SSL connection
        debug('upgrading proxy-connected socket to TLS connection: %o', opts.host);
        opts.socket = socket;
        opts.servername = opts.host;
        opts.host = null;
        opts.hostname = null;
        opts.port = null;
        sock = tls.connect(opts);
        SocketUtil.secureSocket(sock, host);
      }

      cleanup();
      fn(null, sock);
    } else {
      // some other status code that's not 200... need to re-play the HTTP header
      // "data" events onto the socket once the HTTP machinery is attached so that
      // the user can parse and handle the error status code
      cleanup();

      // save a reference to the concat'd Buffer for the `onsocket` callback
      buffers = buffered;

      // need to wait for the "socket" event to re-play the "data" events
      req.once('socket', onsocket);
      fn(null, socket);
    }
  }

  function onsocket (socket) {
    // replay the "buffers" Buffer onto the `socket`, since at this point
    // the HTTP module machinery has been hooked up for the user
    if ('function' == typeof socket.ondata) {
      // node <= v0.11.3, the `ondata` function is set on the socket
      socket.ondata(buffers, 0, buffers.length);
    } else if (socket.listeners('data').length > 0) {
      // node > v0.11.3, the "data" event is listened for directly
      socket.emit('data', buffers);
    } else {
      // never?
      throw new Error('should not happen...');
    }

    // nullify the cached Buffer instance
    buffers = null;
  }

  socket.on('error', onerror);
  socket.on('close', onclose);
  socket.on('end', onend);

  if (socket.read) {
    read();
  } else {
    socket.once('data', ondata);
  }

  var hostname = opts.host + ':' + opts.port;
  var msg = 'CONNECT ' + hostname + ' HTTP/1.1\r\n';
  var auth = proxy.auth;
  if (auth) {
    msg += 'Proxy-Authorization: Basic ' + Buffer.from(auth, 'utf8').toString('base64') + '\r\n';
  }
  msg += 'Host: ' + hostname + '\r\n' +
      'Connection: close\r\n' +
      '\r\n';
  socket.write(msg);
}
234113
function createProxyHandler (proxies, urlRoot) {
  if (!proxies.length) {
    const nullProxy = (request, response, next) => next()
    nullProxy.upgrade = () => {}
    return nullProxy
  }

  function createProxy (request, response, next) {
    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.web(request, response)
    } else {
      return next()
    }
  }

  createProxy.upgrade = function (request, socket, head) {
    // special-case karma's route to avoid upgrading it
    if (request.url.startsWith(urlRoot)) {
      log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`)
      return
    }

    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.ws(request, socket, head)
    }
  }

  return createProxy
}
935990
function WebSocket(url, opt_protocols) {
    var scope = ctorEvent();
    goog.base(this, descriptor);

    /**
     * Underlying WS.
     * @type {!WebSocket}
     * @private
     */
    this.handle_ = arguments.length == 1 ?
        new originalWs(url) :
        new originalWs(url, opt_protocols);

    /**
     * Event type trackers, by name.
     * @type {!Object.<Function>}
     * @private
     */
    this.trackers_ = {};

    /**
     * Properties, accumulated during setup before send().
     * @type {!Object}
     * @private
     */
    this.props_ = {
      'url': url,
      'protocol': opt_protocols
    };

    wtf.trace.Scope.leave(scope);
  }
830028
function (options) {
                var self = this;

                self._requestQueue = []

                self._socketOptions = angular.extend({}, _socketDefaults, options);

                self._socket = new TmpSocket();

                if (self._socketOptions.autoConnect) self.connect();
            }
813855
function WebSocket(socket, ctx) {
  if (!(this instanceof WebSocket))
    return new WebSocket(socket, ctx);

  EventEmitter.call(this);

  this.context = ctx;
  this.socket = socket;
  this.remoteAddress = socket.conn.remoteAddress;
  this.hooks = Object.create(null);
  this.channels = new Map();
  this.auth = false;
  this.filter = null;
  this.prev = null;
  this.next = null;

  this.init();
}