one step above using http.createServer
423290
function host(){
	var app = leachApp(connect())
	for(var x in host.prototype)app[x] = host.prototype[x]
	return app
}
939737
function startServer(serverPromise) {
    var self = this,
        startTime = Date.now(),
        browsersStarting,
        serverTimeout,
        serverProcess = fork(__dirname + '/KarmaWorker.js', { silent: true });

    // Limit the time it can take for a server to start to config.waitForServerTime seconds
    serverTimeout = setTimeout(function() {
        self._setStatus(KarmaServerStatus.DEFUNCT);
        serverPromise.reject(
            'Could not connect to a Karma server on port ' + self._config.port + ' within ' +
            self._config.waitForServerTime + ' seconds'
        );
    }, self._config.waitForServerTime * 1000);

    serverProcess.send({ command: 'start', config: self._config });

    serverProcess.stdout.on('data', function(data) {
        var message = data.toString('utf-8'),
            messageParts = message.split(/\s/g);

        logger.debug(message);

        //this is a hack: because Karma exposes no method of determining when the server is started up we'll dissect the log messages
        if(message.indexOf('Starting browser') > -1) {
            browsersStarting = browsersStarting ? browsersStarting.concat([messageParts[4]]) : [messageParts[4]];
        }
        if(message.indexOf('Connected on socket') > -1) {
            browsersStarting.pop();
            if(browsersStarting && browsersStarting.length === 0) {
                clearTimeout(serverTimeout);
                self._setStatus(KarmaServerStatus.READY);

                logger.info(
                    'Karma server started after %dms and is listening on port %d',
                    (Date.now() - startTime), self._config.port
                );

                serverPromise.resolve(self);
            }
        }
    });

    return serverProcess;
}
953187
async def makeHttpRequest(method, url, payload, headers, retries=utils.MAX_RETRIES, session=None):
    
    retry = -1
    response = None
    implicit = False
    if session is None:
        implicit = True
        session = aiohttp.ClientSession()

    def cleanup():
        if implicit:
            loop = asyncio.get_event_loop()
            loop.run_until_complete(session.close())

    try:
        while True:
            retry += 1
            # if this isn't the first retry then we sleep
            if retry > 0:
                snooze = float(retry * retry) / 10.0
                log.info('Sleeping %0.2f seconds for exponential backoff', snooze)
                await asyncio.sleep(snooze)

            # Seek payload to start, if it is a file
            if hasattr(payload, 'seek'):
                payload.seek(0)

            log.debug('Making attempt %d', retry)
            try:
                with async_timeout.timeout(60):
                    response = await makeSingleHttpRequest(method, url, payload, headers, session)
            except aiohttp.ClientError as rerr:
                if retry < retries:
                    log.warn('Retrying because of: %s' % rerr)
                    continue
                # raise a connection exception
                raise rerr
            except ValueError as rerr:
                log.warn('ValueError from aiohttp: redirect to non-http or https')
                raise rerr
            except RuntimeError as rerr:
                log.warn('RuntimeError from aiohttp: session closed')
                raise rerr
            # Handle non 2xx status code and retry if possible
            status = response.status
            if 500 <= status and status < 600 and retry < retries:
                if retry < retries:
                    log.warn('Retrying because of: %d status' % status)
                    continue
                else:
                    raise exceptions.TaskclusterRestFailure("Unknown Server Error", superExc=None)
            return response
    finally:
        cleanup()
    # This code-path should be unreachable
    assert False, "Error from last retry should have been raised!"
378215
function startRecorderServer(config, onReady, onCommand, onEnd){
    var server = http.createServer(function(req, res){
        if(req.url === '/proxy.pac'){
            var wdproxy = config.wdproxy;
            if(wdproxy){
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                var pacContent = 'function FindProxyForURL(url, host){if(!/^(127.0.0.1|localhost)$/.test(host))return "PROXY '+config.wdproxy+'";\r\nreturn "DIRECT"}';
                res.end(pacContent);
            }
            else{
                res.end('No wdproxy finded!');
            }
        }
    });
    server.listen(0, function(){
        var serverPort = server.address().port;
        console.log('');
        console.log(__('recorder_server_listen_on').green, serverPort);
        onReady(serverPort);
    });
    wsServer = new WebSocketServer({
        httpServer: server,
        autoAcceptConnections: true
    });
    wsServer.on('connect', function(connection) {
        wsConnection = connection;
        sendWsMessage('config', config);
        connection.on('message', function(message) {
            var message = message.utf8Data;
            try{
                message = JSON.parse(message);
            }
            catch(e){};
            var type = message.type;
            switch(type){
                case 'saveCmd':
                    onCommand(message.data);
                    break;
                case 'save':
                    onCommand({
                        cmd: 'end'
                    });
                    setTimeout(function(){
                        wsConnection && wsConnection.close();
                        server.close(function(){
                            onEnd(true);
                        });
                    }, 500);
                    break;
                case 'end':
                    onCommand({
                        cmd: 'end'
                    });
                    setTimeout(function(){
                        wsConnection && wsConnection.close();
                        server.close(function(){
                            onEnd(false);
                        });
                    }, 500);
                    break;
            }
        });
        connection.on('close', function(reasonCode, description) {
            wsConnection = null;
        });
    });
}
948963
function makeHttpRequest(next) {
  var start;

  var httpReq = http.request({
    host: 'localhost',
    port: 1337,
    method: 'POST',
    path: '/upper?page=12',
    headers: {
      'x-to-reverse': 'hello'
    }
  }, function(res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      var time = Date.now() - start;

      var filteredHeaders = _.pick(res.headers, 'x-reversed');
      console.log('FROM HTTP');
      console.log('  status :', res.statusCode);
      console.log('  headers:', JSON.stringify(filteredHeaders));
      console.log('  body   :', body);
      console.log('  time   :', time);

      common.verify(function() {
        filteredHeaders.should.eql({ 'x-reversed': 'olleh' });
        JSON.parse(body).should.eql({ data: 'HELLO-WORLD' });
        common.shouldBeDynamicallyTimed(time);
      });

      console.log();

      next();
    });
  });

  start = Date.now();
  httpReq.end('hello-world');
}
247030
def serveInBackground(port, serverName, prefix='/status/'):
  """"""
  import flask, threading
  from wsgiref.simple_server import make_server
  app = flask.Flask(__name__)
  registerStatsHandler(app, serverName, prefix)
  server = threading.Thread(target=make_server('', port, app).serve_forever)
  server.daemon = True
  server.start()
  return server
179061
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

  this.headers = options.headers || {};

  this.cache = options.cache === undefined ? 3600 : options.cache; // in seconds.
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.gzip = options.gzip === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    contentType: this.contentType,
//    handleError: typeof options.proxy !== 'string'
    handleError: (!options.fallback || typeof options.proxy === 'string')
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      });
    });
  }

  if (options.fallback) {
    before.push(function (req, res) {
      if (res.statusCode === 404) {
        res.redirect(options.fallback.address, 301);
      }
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
559700
def _build_http_client(cls, session: AppSession):
        '''
        '''
        # TODO:
        # recorder = self._build_recorder()

        stream_factory = functools.partial(
            HTTPStream,
            ignore_length=session.args.ignore_length,
            keep_alive=session.args.http_keep_alive)

        return session.factory.new(
            'HTTPClient',
            connection_pool=session.factory['ConnectionPool'],
            stream_factory=stream_factory
         )
529904
function Http(ip) {
    Http['super_'].call(this);

    /**
     * @property options
     * @private
     * @type {{hostname: String, port: Number, path: String, method: String}}
     */
    this.options = {
        hostname: ip,
        port: 80,
        path: '/rpc',
        method: 'POST',
        headers: {
            'Content-Length': 0
        }
    };
}
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
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
        }
1129750
function startServer(devServerUrl) {
  const { port: devServerPort } = url.parse(devServerUrl);
  return choosePort(HOST, devServerPort - 1)
    .then(port => {
      if (port == null) {
        // We have not found a port.
        return;
      }
      const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
      const appName = require(paths.appPackageJson).name;
      const urls = prepareUrls(protocol, HOST, port);
      // Directly set the HOST, PORT and PROTOCOL, which would be used in DefinePlugin
      // let the webpack define the public path correctly in DefinePlugin
      process.env.HOST = HOST;
      process.env.PORT = port;
      process.env.PROTOCOL = protocol;
      process.env.PUBLIC_URL = url.format({ protocol: protocol, hostname: HOST, port: devServerPort });

      // Create a webpack compiler that is configured with custom messages.
      const webpackConfig = serverlize(paths, config, `${devServerUrl}/`);
      const compiler = createCompiler(webpack, webpackConfig, appName, urls, useYarn);
      let browserOpened = false;
      compiler.watch({
        quiet: true,
        stats: 'none'
      }, (err, stats) => {
        if (!browserOpened) {
          openBrowser(urls.localUrlForBrowser);
          browserOpened = true;
        }
        if (err) {
          console.log(chalk.red('Failed to compile.\n'));
          printBuildError(err);
          return;
        }
        if (isInteractive) {
          clearConsole();
        }
        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;
          }
          console.log(chalk.red('Failed to compile.\n'));
          printBuildError(new Error(messages.errors.join('\n\n')));
          return;
        }
        console.log(chalk.green('Compiled successfully!'));
        console.log(
          `To create a production build, use ` +
            `${chalk.cyan(`${useYarn ? 'yarn' : 'npm run'} build:server`)}.`
        );
        console.log('Note that all client side errors or warnings are suppressed.');
        console.log();
      });
    })
    .catch(err => {
      if (err && err.message) {
        console.log(err.message);
      }
      process.exit(1);
    });
}
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);

}
577252
function runWebServerInProcess(rawConfig, serverConfig, emitter) {
  var server = require('./server.js');
  
  if (serverConfig.command == 'stop') {
    logger.info('stopping server');
    return server.stop();
  }
  
  var app = server.listen(rawConfig, serverConfig, function(err, newCommandName, newConfig, finalCallback) {
    if (err) { 
      logger.error("Error: " + err);
      if (callback) callback(err);
    } else {
      emitter.emit(newCommandName, newConfig, finalCallback);
    }
  });
}
1338646
function nextCreate(
  filesPromise,
  serveStaticFile,
  serveFile,
  injector,
  basePath,
  urlRoot,
  upstreamProxy
) {
  var prevMiddleware = prevCreate(
    filesPromise,
    serveStaticFile,
    serveFile,
    injector,
    basePath,
    urlRoot,
    upstreamProxy
  );
  return function nextMiddleware(request, response, next) {
    var requestUrl = request.normalizedUrl.replace(/\?.*/, '');
    var prevWrite;
    var prevEnd;
    requestUrl = requestUrl.substr(urlRoot.length - 1);
    if (requestUrl === '/context.html' &&
        toplevelScriptIntegrity &&
        toplevelScriptIntegrity.startsWith('sha') &&
        stylesheetIntegrity &&
        stylesheetIntegrity.startsWith('sha')) {
      prevWrite = response.write;
      prevEnd = response.end;
      // eslint-disable-next-line no-param-reassign
      response.write = function nextWrite(chunk, encoding, callback) {
        prevWrite.call(response, addIntegrityTags(chunk), encoding, callback);
      };
      response.end = function nextEnd(chunk, encoding, callback) {
        prevEnd.call(response, addIntegrityTags(chunk), encoding, callback);
      };
    }
    return prevMiddleware(request, response, next);
  };
}
976273
function createServer(webhook)
{
  var self = this

  var onError = this.emit.bind(this, 'error')

  var port     = webhook.port     || 0
  var hostname = webhook.hostname || HOSTNAME

  var server = http.createServer(function(req, res)
  {
    if(req.method === 'GET')
    {
      res.end()

      return self.push(parse(req.url).query)
    }

    req.pipe(concat(function(body)
    {
      res.end()

      self.push(body.toString())
    }))
  })
  .listen(port, hostname, function()
  {
    var address = this.address()

    if(hostname === HOSTNAME) hostname = getHostname()

    if(!hostname)
    {
      self.emit('error', new Error("There's no public available interfaces"))

      return this.close()
    }

    self.emit('open', 'http://'+hostname+':'+address.port)
  })
  .on('error'      , onError)
  .on('clientError', onError)

  return server
}
1107809
function WebServer(data) {
  // Use a closure to preserve `this`
  var self = this;
  self.data = data;

  this.RequestHandler = bind(this.RequestHandler, this);
  this.callbackExecutor = bind(this.callbackExecutor, this);

  self.server = http.createServer(self.RequestHandler);

  // Use random port if port settings is not provided.
  if (!self.data.port) {
    self.data.port = 0;
  }

  // Use address if provided.
  if (self.data.hostname) {
    self.server.listen(self.data.port, self.data.hostname);
  } else {
    self.server.listen(self.data.port);
  }

  self.server.on('listening', function() {
    self.debug.log('Listen on :%s', self.server.address().port);
  });
}