Yes, SockJS is weird, but it's hard to work out expected server behaviour when there's no spec
510457
@Override
  public synchronized void close() {
    if (endHandler != null) {
      endHandler.handle(null);
    }
    closed = true;
    if (listener != null && handleCalled) {
      listener.sessionClosed();
    }
  }
1056160
function HybridConnectionsWebSocketServer(options, callback) {
  if (this instanceof HybridConnectionsWebSocketServer === false) {
    return new HybridConnectionsWebSocketServer(options, callback);
  }

  EventEmitter.call(this);

  options = Object.assign({
    server: null,
    token: null,
    id: null,
    verifyClient: null,
    handleProtocols: null,
    disableHixie: false,
    clientTracking: true,
    perMessageDeflate: true,
    maxPayload: 100 * 1024 * 1024,
    backlog: null // use default (511 as implemented in net.js)
  }, options);

  if (!isDefinedAndNonNull(options, 'server')) {
    throw new TypeError('\'server\' must be provided');
  }

  if (!isDefinedAndNonNull(options, 'token')) {
    throw new TypeError('A \'token\' string or function must be provided');
  }

  var self = this;

  this.listenUri = options.server;
  if (isDefinedAndNonNull(options, 'id')) {
    this.listenUri = listenUri + '&id=' + options.id;
  }

  this.closeRequested = false;
  this.options = options;
  this.path = options.path;
  this.clients = [];

  connectControlChannel(this);
}
1188665
function normalizeServer(server) {
  // normalize hostname
  if (!reProtocol.test(server)) {
    server = 'http://' + server;
  }
  server = url.parse(server);

  return {
    protocol: server.protocol,
    hostname: server.hostname,
    auth: server.auth,
    pathname: server.pathname,
    port: parseInt(server.port, 10) || (server.protocol === 'https:' ? 443 : 80)
  };
}
1037348
function Socket() {
  this.socks = [];
  this.settings = {};
  this.connected = false;
  this.set('identity', String(process.pid));
  this.set('retry timeout', 100);
  this.set('retry max timeout', 5000);
}
1119584
function() {
    this.cantWebsocket = vAPI.cantWebsocket;
    this.reBadDomainOptChars = /[*+?^${}()[\]\\]/;
    this.reHostnameRule1 = /^[0-9a-z][0-9a-z.-]*[0-9a-z]$/i;
    this.reHostnameRule2 = /^[0-9a-z][0-9a-z.-]*[0-9a-z]\^?$/i;
    this.reCleanupHostnameRule2 = /\^$/g;
    this.reCanTrimCarets1 = /^[^*]*$/;
    this.reCanTrimCarets2 = /^\^?[^^]+[^^][^^]+\^?$/;
    this.reHasUppercase = /[A-Z]/;
    this.reIsolateHostname = /^(\*?\.)?([^\x00-\x24\x26-\x2C\x2F\x3A-\x5E\x60\x7B-\x7F]+)(.*)/;
    this.reHasUnicode = /[^\x00-\x7F]/;
    this.reWebsocketAny = /^ws[s*]?(?::\/?\/?)?\*?$/;
    this.reBadCSP = /(?:^|;)\s*report-(?:to|uri)\b/;
    this.domainOpt = '';
    this.noTokenHash = µb.urlTokenizer.noTokenHash;
    this.unsupportedTypeBit = this.bitFromType('unsupported');
    // All network request types to bitmap
    //   bring origin to 0 (from 4 -- see typeNameToTypeValue)
    //   left-shift 1 by the above-calculated value
    //   subtract 1 to set all type bits
    this.allNetRequestTypeBits = (1 << (otherTypeBitValue >>> 4)) - 1;
    this.reset();
}
299936
function issecure(req, trustProxy) {
  // socket is https server
  if (req.connection && req.connection.encrypted) {
    return true;
  }

  // do not trust proxy
  if (trustProxy === false) {
    return false;
  }

  // no explicit trust; try req.secure from express
  if (trustProxy !== true) {
    return req.secure === true
  }

  // read the proto from x-forwarded-proto header
  var header = req.headers['x-forwarded-proto'] || '';
  var index = header.indexOf(',');
  var proto = index !== -1
    ? header.substr(0, index).toLowerCase().trim()
    : header.toLowerCase().trim()

  return proto === 'https';
}
1098555
private CompletableFuture<Void> bootstrapServer() {
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
        new WriteBufferWaterMark(8 * 1024, 32 * 1024));
    b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    b.childOption(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(serverGroup, clientGroup);
    b.channel(serverChannelClass);
    if (enableNettyTls) {
      try {
        b.childHandler(new SslServerChannelInitializer());
      } catch (SSLException e) {
        return Futures.exceptionalFuture(e);
      }
    } else {
      b.childHandler(new BasicServerChannelInitializer());
    }
    return bind(b);
  }
1071049
private static ServerSocket random() throws IOException {
        final ServerSocket skt = new ServerSocket(0);
        skt.setReuseAddress(true);
        return skt;
    }
495065
function startBrowserSync(serverRoot) {

    console.log('Starting BrowserSync on port ' + 8010 + ' for ' + serverRoot);

    var options = {
        //proxy: 'localhost:' + port,
        port: 8010,
        ws: true,
        server: {
            baseDir: serverRoot
        },
        reloadDelay: 2000
    };

    browserSync.init(options);

}
520744
private void processReply(ProxyMessage reply)throws SocksException{
      localPort = reply.port;
      /*
       * If the server have assigned same host as it was contacted on
       * it might return an address of all zeros
       */
      if(reply.host.equals("0.0.0.0")){
         localIP = proxy.proxyIP;
         localHost = localIP.getHostName();
      }else{
         localHost = reply.host;
         localIP = reply.ip;
      }
   }
1122194
def resolve_real_bind_addr(socket_):
        """"""
        # FIXME: keep requested bind_addr separate real bound_addr (port
        # is different in case of ephemeral port 0)
        bind_addr = socket_.getsockname()
        if socket_.family in (
            # Windows doesn't have socket.AF_UNIX, so not using it in check
            socket.AF_INET,
            socket.AF_INET6,
        ):
            """UNIX domain sockets are strings or bytes.

            In case of bytes with a leading null-byte it's an abstract socket.
            """
            return bind_addr[:2]
        return bind_addr
827388
function createOptionsForServerSpec(serverSpec) {
    var options = {
        forceNew: true,            // Make a new connection each time
        reconnection: false        // Don't try and reconnect automatically
    };

    // If the server spec contains a socketResource setting we use
    // that otherwise leave the default ('/socket.io/')
    if(serverSpec.socket.socketResource) {
        options.resource = serverSpec.socket.socketResource;
    }
    return options;
}
217886
def _wait_for_io_events(socks, events, timeout=None):
    
    if not HAS_SELECT:
        raise ValueError('Platform does not have a selector')
    if not isinstance(socks, list):
        # Probably just a single socket.
        if hasattr(socks, "fileno"):
            socks = [socks]
        # Otherwise it might be a non-list iterable.
        else:
            socks = list(socks)
    with DefaultSelector() as selector:
        for sock in socks:
            selector.register(sock, events)
        return [key[0].fileobj for key in
                selector.select(timeout) if key[1] & events]
563780
function (options, callbackFn) {
            var self = this;

            //compensate for optional options parm
            if (typeof options === 'function') {
                callbackFn = options;
                options = {};
            }

            //assign default port
            options.port = options.port || 1061;
            options.host = options.host || 'localhost';
            options.hostAndPort = 'http://' + options.host + ':' + options.port;
            options.eventStreamPath = require('path').normalize(__dirname + '/../temp/events.txt');
            options.phantomjsPath = options.phantomjsPath || 'phantomjs';

            options.debug && console.log('creating proxy to %s', options.hostAndPort);

            this.options = options;

            //try starting server
            createServer.call(self, options, function (proxy) {
                callbackFn.call(self, proxy);
            });

            return this;//return this to chain end
        }
22386
function buildServer() {
  console.log();
  console.log(`${chalk.cyan('SERVER-SIDE')}`);
  console.log('===========================================================');
  fs.emptyDirSync(paths.appServerBuild);
  console.log('Creating a server-side production build...');

  let compiler = webpack(serverlize(paths, config));
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err);
      } 
      const messages = formatWebpackMessages(stats.toJson({}, true));
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1;
        }
        return reject(new Error(messages.errors.join('\n\n')));
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' ||
          process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
          )
        );
        return reject(new Error(messages.warnings.join('\n\n')));
      }
      return resolve({
        stats,
        warnings: messages.warnings,
      });
    });
  }).then(
    ({ stats, warnings }) => {
      if (warnings.length) {
        console.log(chalk.yellow('Compiled with warnings.\n'));
        console.log(warnings.join('\n\n'));
        console.log(
          '\nSearch for the ' +
            chalk.underline(chalk.yellow('keywords')) +
            ' to learn more about each warning.'
        );
        console.log(
          'To ignore, add ' +
            chalk.cyan('// eslint-disable-next-line') +
            ' to the line before.\n'
        );
      } else {
        console.log(chalk.green('Compiled successfully.\n'));
      }
      console.log(`The ${chalk.cyan(path.relative(process.cwd(), paths.appServerBuild))} folder is ready.`);
      console.log(`You may run it in ${chalk.cyan('node')} environment`);
      console.log();
      console.log(`  ${chalk.cyan('node')} ${chalk.cyan(path.relative(process.cwd(), paths.appServerBuild))}`);
      console.log();
    },
    err => {
      console.log(chalk.red('Failed to compile.\n'));
      printBuildError(err);
      process.exit(1);
    }
  );
}
1274157
function (host, port, prefix, suffix, globalize, cacheDns, mock,
    globalTags, maxBufferSize, bufferFlushInterval, telegraf, sampleRate, protocol) {
  let options = host || {};
  const self = this;

  // Adding options below is DEPRECATED.  Use the options object instead.
  if (arguments.length > 1 || typeof(host) === 'string') {
    options = {
      host        : host,
      port        : port,
      prefix      : prefix,
      suffix      : suffix,
      globalize   : globalize,
      cacheDns    : cacheDns,
      mock        : mock === true,
      globalTags  : globalTags,
      maxBufferSize : maxBufferSize,
      bufferFlushInterval: bufferFlushInterval,
      telegraf    : telegraf,
      sampleRate  : sampleRate,
      protocol    : protocol
    };
  }

  const createSocket = function createSocket(instance, args) {
    let socket;
    let errMessage;

    if (args.protocol === 'tcp') {
      try {
        socket = net.connect(args.port, args.host);
        socket.setKeepAlive(true);
      } catch (e) {
        errMessage = `Could not establish connection to ${args.host}:${args.port}`;
        if (instance.errorHandler) {
          instance.errorHandler(new Error(errMessage));
        } else {
          console.log(errMessage);
        }
      }
    } else {
      socket = dgram.createSocket('udp4');
    }

    return socket;
  };

  // hidden global_tags option for backwards compatibility
  options.globalTags = options.globalTags || options.global_tags;

  this.protocol    = (options.protocol && options.protocol.toLowerCase());
  this.host        = options.host || process.env.DD_AGENT_HOST || 'localhost';
  this.port        = options.port || parseInt(process.env.DD_DOGSTATSD_PORT, 10) || 8125;
  this.prefix      = options.prefix || '';
  this.suffix      = options.suffix || '';
  this.socket      = options.isChild ? options.socket : createSocket(this, {
    host: this.host,
    port: this.port,
    protocol: this.protocol
  });
  this.mock        = options.mock;
  this.globalTags  = typeof options.globalTags === 'object' ?
      helpers.formatTags(options.globalTags, options.telegraf) : [];
  if (process.env.DD_ENTITY_ID) {
    this.globalTags = this.globalTags.filter((item) => {
      return item.indexOf('dd.internal.entity_id:') !== 0;
   });
    this.globalTags.push('dd.internal.entity_id:'.concat(helpers.sanitizeTags(process.env.DD_ENTITY_ID)));
  }
  this.telegraf    = options.telegraf || false;
  this.maxBufferSize = options.maxBufferSize || 0;
  this.sampleRate  = options.sampleRate || 1;
  this.bufferFlushInterval = options.bufferFlushInterval || 1000;
  this.bufferHolder = options.isChild ? options.bufferHolder : { buffer: '' };
  this.errorHandler = options.errorHandler;

  // If we're mocking the client, create a buffer to record the outgoing calls.
  if (this.mock) {
    this.mockBuffer = [];
  }

  // We only want a single flush event per parent and all its child clients
  if (!options.isChild && this.maxBufferSize > 0) {
    this.intervalHandle = setInterval(this.onBufferFlushInterval.bind(this), this.bufferFlushInterval);
  }

  if (options.isChild) {
    if (options.dnsError) {
      this.dnsError = options.dnsError;
    }
  } else if (options.cacheDns === true) {
    dns.lookup(options.host, (err, address) => {
      if (err === null) {
        self.host = address;
      } else {
        self.dnsError = err;
      }
    });
  }

  if (!options.isChild && options.errorHandler) {
    this.socket.on('error', options.errorHandler);
  }

  if (options.globalize) {
    global.statsd = this;
  }

  if (options.useDefaultRoute) {
    const defaultRoute = helpers.getDefaultRoute();
    if (defaultRoute) {
      console.log(`Got ${defaultRoute} for the system's default route`);
      this.host = defaultRoute;
    }
  }

  this.messagesInFlight = 0;
  this.CHECKS = {
    OK: 0,
    WARNING: 1,
    CRITICAL: 2,
    UNKNOWN: 3,
  };
}
239784
function createServers(conf) {
  var seenKeys = map.create();

  var servers = _.map(conf.search('server'), function(serverNode) {
    var listenNode = serverNode.getOne('listen');
    if (!listenNode)
      throwForNode(serverNode,
          new Error('Required "listen" directive is missing'));

    var port = serverNode.getValues('listen').port;
    if (typeof port === 'undefined')
      port = 80;
    if (port <= 0)
      throwForNode(listenNode, new Error('Invalid port number'));

    var host = serverNode.getValues('listen').host || '::';
    if (host === '*')
      host = '::';

    if (!iputil.isValid(host)) {
      throwForNode(listenNode,
          new Error('Invalid IP address "' + host + '"'));
    }

    if (iputil.hasZone(host)) {
      throwForNode(listenNode,
          new Error(`Invalid IP address "${host}"--zone IDs are not currently supported`))
    }

    var serverNames = serverNode.getValues('server_name').names;

    // Read all locations. Use post-order traversal so that nested locs
    // get priority over their parents.
    var locations = _.chain(serverNode.search('location', false, true))
    .map(createLocation)
    .compact()
    .value();

    // We get the templateDir at the server level so that a global or server-
    // wide templateDir can be attached to the request directly. We may need
    // this if a page gets returns without a matching AppSpec (like a 404).
    var templateDir = serverNode.getValues('template_dir').dir;

    _.each(serverNames || [''], function(serverName) {
      var key = host + ':' + port;
      if (serverName !== '')
        key += '(' + serverName + ')';
      if (seenKeys[key])
        throwForNode(listenNode,
            new Error(key + ' combination conflicts with earlier server definition'));
      seenKeys[key] = true;
    });

    return new ServerRouter(port, host, serverNames, locations, templateDir);
  });

  return servers;
}