Start the mock server by either using a provided plugin in the format
{ mockServer: {plugin} } or { mockServer: { plugin: {plugin},  } }

or started manually using start/stop async callbacks in the format
{ mockServer: { start: func({port}), stop: ... } }
438441
function (options, callback) {
    var log = this.log;

    if (this.startMockServerFunc) {
      log('manual mock server startup');
      // app specific test runner does most of the work
      this.startMockServerFunc(options, callback);
    } else if (this.mockServerPlugin) {
      log('using mock server plugin');
      // adapter does most of the work
      var mockServer = this.mockServer = new Hapi.Server(this.mockServerOptions);
      mockServer.connection({ port: this.mocksPort });
      mockServer.register(this.mockServerPlugin, function (err) {
        if (err) {
          log('registered mock server plugin: ' + err.message);
          return callback(err);
        }
        log('registered mock server plugin;  starting mock server');
        mockServer.start(callback);
      });
    } else {
      log('no mock server setup/teardown functions provided *and* no plugin provided... not starting mock server');
      callback();
    }
  }
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
        }
310369
def runserver(**config_kwargs):
    
    # force a full reload in sub processes so they load an updated version of code, this must be called only once
    set_start_method('spawn')

    config = Config(**config_kwargs)
    config.import_app_factory()
    loop = asyncio.get_event_loop()

    loop.run_until_complete(check_port_open(config.main_port, loop))

    aux_app = create_auxiliary_app(
        static_path=config.static_path_str,
        static_url=config.static_url,
        livereload=config.livereload,
    )

    main_manager = AppTask(config, loop)
    aux_app.on_startup.append(main_manager.start)
    aux_app.on_shutdown.append(main_manager.close)

    if config.static_path:
        static_manager = LiveReloadTask(config.static_path, loop)
        logger.debug('starting livereload to watch %s', config.static_path_str)
        aux_app.on_startup.append(static_manager.start)
        aux_app.on_shutdown.append(static_manager.close)

    url = 'http://{0.host}:{0.aux_port}'.format(config)
    logger.info('Starting aux server at %s ◆', url)

    if config.static_path:
        rel_path = config.static_path.relative_to(os.getcwd())
        logger.info('serving static files from ./%s/ at %s%s', rel_path, url, config.static_url)

    return aux_app, config.aux_port, loop, AuxAccessLogger
206792
def start_server():
    """"""
    parser = argparse.ArgumentParser(description="Opens a browser-based "
                                     "client that interfaces with the "
                                     "chemical format converter.")
    parser.add_argument('--debug', action="store_true", help="Prints all "
                        "transmitted data streams.")
    parser.add_argument('--port', type=int, default=8000, help="The port "
                        "on which to serve the website.")
    parser.add_argument('--timeout', type=int, default=5, help="The maximum "
                        "time, in seconds, allowed for a process to run "
                        "before returning an error.")
    parser.add_argument('--workers', type=int, default=2, help="The number of "
                        "worker processes to use with the server.")
    parser.add_argument('--no-browser', action="store_true", help="Disables "
                        "opening a browser window on startup.")
    global args
    args = parser.parse_args()

    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    handlers = [(r'/', IndexHandler), (r'/websocket', WebSocket),
                (r'/static/(.*)', tornado.web.StaticFileHandler,
                 {'path': os.path.normpath(os.path.dirname(__file__))})]
    application = tornado.web.Application(handlers)
    application.listen(args.port)

    if not args.no_browser:
        webbrowser.open('http://localhost:%d/' % args.port, new=2)

    try:
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        sys.stderr.write("Received keyboard interrupt. Stopping server.\n")
        tornado.ioloop.IOLoop.instance().stop()
        sys.exit(1)
1210574
async function start() {
  if (server) return server;
  server = express();
  server.use(errorOverlayMiddleware());
  server.use(express.static(path.resolve(__dirname, '../public')));

  // Configure client-side hot module replacement
  const clientConfig = webpackConfig.find(config => config.name === 'client');
  clientConfig.entry.client = ['./tools/lib/webpackHotDevClient']
    .concat(clientConfig.entry.client)
    .sort((a, b) => b.includes('polyfill') - a.includes('polyfill'));
  clientConfig.output.filename = clientConfig.output.filename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.module.rules = clientConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure server-side hot module replacement
  const serverConfig = webpackConfig.find(config => config.name === 'server');
  serverConfig.output.hotUpdateMainFilename = 'updates/[hash].hot-update.json';
  serverConfig.output.hotUpdateChunkFilename =
    'updates/[id].[hash].hot-update.js';
  serverConfig.module.rules = serverConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure compilation
  await run(clean);
  const multiCompiler = webpack(webpackConfig);
  const clientCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'client',
  );
  const serverCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'server',
  );
  const clientPromise = createCompilationPromise(
    'client',
    clientCompiler,
    clientConfig,
  );
  const serverPromise = createCompilationPromise(
    'server',
    serverCompiler,
    serverConfig,
  );

  // https://github.com/webpack/webpack-dev-middleware
  server.use(
    webpackDevMiddleware(clientCompiler, {
      publicPath: clientConfig.output.publicPath,
      logLevel: 'silent',
      watchOptions,
    }),
  );

  // https://github.com/glenjamin/webpack-hot-middleware
  server.use(webpackHotMiddleware(clientCompiler, { log: false }));

  let appPromise;
  let appPromiseResolve;
  let appPromiseIsResolved = true;
  serverCompiler.hooks.compile.tap('server', () => {
    if (!appPromiseIsResolved) return;
    appPromiseIsResolved = false;
    // eslint-disable-next-line no-return-assign
    appPromise = new Promise(resolve => (appPromiseResolve = resolve));
  });

  let app;
  server.use((req, res) => {
    appPromise
      .then(() => app.handle(req, res))
      .catch(error => console.error(error));
  });

  function checkForUpdate(fromUpdate) {
    const hmrPrefix = '[\x1b[35mHMR\x1b[0m] ';
    if (!app.hot) {
      throw new Error(`${hmrPrefix}Hot Module Replacement is disabled.`);
    }
    if (app.hot.status() !== 'idle') {
      return Promise.resolve();
    }
    return app.hot
      .check(true)
      .then(updatedModules => {
        if (!updatedModules) {
          if (fromUpdate) {
            console.info(`${hmrPrefix}Update applied.`);
          }
          return;
        }
        if (updatedModules.length === 0) {
          console.info(`${hmrPrefix}Nothing hot updated.`);
        } else {
          console.info(`${hmrPrefix}Updated modules:`);
          updatedModules.forEach(moduleId =>
            console.info(`${hmrPrefix} - ${moduleId}`),
          );
          checkForUpdate(true);
        }
      })
      .catch(error => {
        if (['abort', 'fail'].includes(app.hot.status())) {
          console.warn(`${hmrPrefix}Cannot apply update.`);
          delete require.cache[require.resolve('../build/server')];
          // eslint-disable-next-line global-require, import/no-unresolved
          app = require('../build/server').default;
          console.warn(`${hmrPrefix}App has been reloaded.`);
        } else {
          console.warn(
            `${hmrPrefix}Update failed: ${error.stack || error.message}`,
          );
        }
      });
  }

  serverCompiler.watch(watchOptions, (error, stats) => {
    if (app && !error && !stats.hasErrors()) {
      checkForUpdate().then(() => {
        appPromiseIsResolved = true;
        appPromiseResolve();
      });
    }
  });

  // Wait until both client-side and server-side bundles are ready
  await clientPromise;
  await serverPromise;

  const timeStart = new Date();
  console.info(`[${format(timeStart)}] Launching server...`);

  // Load compiled src/server.js as a middleware
  // eslint-disable-next-line global-require, import/no-unresolved
  app = require('../build/server').default;
  appPromiseIsResolved = true;
  appPromiseResolve();

  // Launch the development server with Browsersync and HMR
  await new Promise((resolve, reject) =>
    browserSync.create().init(
      {
        // https://www.browsersync.io/docs/options
        server: 'src/server.js',
        middleware: [server],
        open: !process.argv.includes('--silent'),
        ...(isDebug ? {} : { notify: false, ui: false }),
      },
      (error, bs) => (error ? reject(error) : resolve(bs)),
    ),
  );

  const timeEnd = new Date();
  const time = timeEnd.getTime() - timeStart.getTime();
  console.info(`[${format(timeEnd)}] Server launched after ${time} ms`);
  return server;
}
283110
public void start() {
        logger.info("\n###starting...");
        try {
            Container container = this.getActualContainer();
            Server server = new ContainerServer(container);
            connection = new SocketConnection(server);
            SocketAddress address = new InetSocketAddress(port);
            socketAddress =(InetSocketAddress) connection.connect(address);
            this.isRunning = true;
            logger.info("\n#Simulator: " + this.getSimulatorName() +
                        "\n#started. " +
                        "\nListening at port: " + socketAddress.getPort());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
1037336
def start_simple_server():
	""
	args = _get_args()
	addr = ('', args.port)
	DebuggingServer(addr, None)
	asyncore.loop()
933056
void initialize()
    {
        if (m_backend == BackendTarget.NONE) {
            m_non_voltdb_backend = null;
            m_ee = new MockExecutionEngine();
        }
        else if (m_backend == BackendTarget.HSQLDB_BACKEND) {
            m_non_voltdb_backend = HsqlBackend.initializeHSQLBackend(m_siteId, m_context);
            m_ee = new MockExecutionEngine();
        }
        else if (m_backend == BackendTarget.POSTGRESQL_BACKEND) {
            m_non_voltdb_backend = PostgreSQLBackend.initializePostgreSQLBackend(m_context);
            m_ee = new MockExecutionEngine();
        }
        else if (m_backend == BackendTarget.POSTGIS_BACKEND) {
            m_non_voltdb_backend = PostGISBackend.initializePostGISBackend(m_context);
            m_ee = new MockExecutionEngine();
        }
        else {
            m_non_voltdb_backend = null;
            m_ee = initializeEE();
        }
        m_ee.loadFunctions(m_context);

        m_snapshotter = new SnapshotSiteProcessor(m_scheduler,
        m_snapshotPriority,
        new SnapshotSiteProcessor.IdlePredicate() {
            @Override
            public boolean idle(long now) {
                return (now - 5) > m_lastTxnTime;
            }
        });
    }
759268
public void start(Path basetDir, Path sampleDir, SampleStartedCallback callback) {

        JettyMavenPluginStdoutListener listener = new JettyMavenPluginStdoutListener();
        MavenProject.load(basetDir).mvnw("-f", sampleDir.toString()).stdout(listener)
                .executeAsync();

        ExecutorContainer.get().execute(() -> {
            callback.onStarted(listener.isSuccess());
        });
    }
202648
def start_server(self, addr='', port=8000):
        
        if self._multiprocess_on:
            raise SanicPrometheusError(
                "start_server can not be used when multiprocessing " +
                "is turned on")
        start_http_server(addr=addr, port=port)
568707
private synchronized void start(InetSocketAddress inetSocketAddress) throws IOException {
    if (started) throw new IllegalStateException("start() already called");
    started = true;

    executor = Executors.newCachedThreadPool(Util.threadFactory("MockWebServer", false));
    this.inetSocketAddress = inetSocketAddress;

    if (serverSocketFactory == null) {
      serverSocketFactory = ServerSocketFactory.getDefault();
    }
    serverSocket = serverSocketFactory.createServerSocket();

    // Reuse if the user specified a port
    serverSocket.setReuseAddress(inetSocketAddress.getPort() != 0);
    serverSocket.bind(inetSocketAddress, 50);

    port = serverSocket.getLocalPort();
    executor.execute(new NamedRunnable("MockWebServer %s", port) {
      @Override protected void execute() {
        try {
          logger.info(MockWebServer.this + " starting to accept connections");
          acceptConnections();
        } catch (Throwable e) {
          logger.log(Level.WARNING, MockWebServer.this + " failed unexpectedly", e);
        }

        // Release all sockets and all threads, even if any close fails.
        closeQuietly(serverSocket);
        for (Iterator<Socket> s = openClientSockets.iterator(); s.hasNext(); ) {
          closeQuietly(s.next());
          s.remove();
        }
        for (Iterator<Http2Connection> s = openConnections.iterator(); s.hasNext(); ) {
          closeQuietly(s.next());
          s.remove();
        }
        dispatcher.shutdown();
        executor.shutdown();
      }

      private void acceptConnections() throws Exception {
        while (true) {
          Socket socket;
          try {
            socket = serverSocket.accept();
          } catch (SocketException e) {
            logger.info(MockWebServer.this + " done accepting connections: " + e.getMessage());
            return;
          }
          SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
          if (socketPolicy == DISCONNECT_AT_START) {
            dispatchBookkeepingRequest(0, socket);
            socket.close();
          } else {
            openClientSockets.add(socket);
            serveConnection(socket);
          }
        }
      }
    });
  }
984285
function startWorkerPoolServer(options, listenCallback)
{
	var workerPool = createWorkerPool();
	var server = createServer(options);
	var logConnection = getOption(options, 'logConnection', true);
	var port = getOption(options, 'port', 0);

	server.on('client', (client) => {
		
		client.on('RGST', (msg) => {
			workerPool.addClient(client);
		});
		
		client.on('error', (e) => {
			workerPool.deleteClient(client);
		});
		
		client.on('close', () => {
			workerPool.deleteClient(client);
		});
	});
	
	server.listen({port: port}, () => {
		if ( logConnection )
		{
			console.log('LISTEN ' + port);
		}
		if ( listenCallback )
		{
			listenCallback(server);
		}
	});
	
	return workerPool;
}
293979
public void startup() {
        if (isRunning) return;

        Executors.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                DispatcherHandler handler = new DispatcherHandler(AndServer.getContext());
                ComponentRegister register = new ComponentRegister(AndServer.getContext());
                register.register(handler, mGroup);

                mHttpServer = ServerBootstrap.bootstrap()
                    .setSocketConfig(SocketConfig.custom()
                        .setSoKeepAlive(true)
                        .setSoReuseAddress(true)
                        .setSoTimeout(mTimeout)
                        .setTcpNoDelay(true)
                        .build())
                    .setConnectionConfig(
                        ConnectionConfig.custom().setBufferSize(4 * 1024).setCharset(Charsets.UTF_8).build())
                    .setLocalAddress(mInetAddress)
                    .setListenerPort(mPort)
                    .setSslContext(mSSLContext)
                    .setSslSetupHandler(new SSLInitializerWrapper(mSSLInitializer))
                    .setServerInfo("AndServer/2.0.0")
                    .registerHandler("*", handler)
                    .setExceptionLogger(ExceptionLogger.NO_OP)
                    .create();
                try {
                    isRunning = true;
                    mHttpServer.start();

                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onStarted();
                        }
                    });
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            mHttpServer.shutdown(3, TimeUnit.SECONDS);
                        }
                    });
                } catch (final Exception e) {
                    Executors.getInstance().post(new Runnable() {
                        @Override
                        public void run() {
                            if (mListener != null) mListener.onException(e);
                        }
                    });
                }
            }
        });
    }
811764
def _start_server(bindaddr, port, hostname, folder):
    """"""
    import asyncio
    from .httpserver import HttpProtocol
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(lambda: HttpProtocol(hostname, folder),
                                   bindaddr,
                                   port)
    server = loop.run_until_complete(coroutine)

    print('Starting server on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
399607
def start(self, blocking=False):
        
        self.debug("()")
        # Start the plugins
        for plugin in self.plugins:
            try:
                # Inject self into plugin
                plugin.controller = self
                plugin.start(blocking=False)
            except:
                self.exception(
                    u"Failed to start plugin {}".format(plugin.name)
                )
                raise PluginStartException(
                    "Starting one or more plugins failed"
                )
        super(CrowdController, self).start(blocking=blocking)
423025
def start(self):
        
        if self.resultdir:
            for lname in self.mock_logfiles:
                self.logfiles[lname] = self.build.path_module.join(self.resultdir,
                                                                   lname)
        else:
            for lname in self.mock_logfiles:
                self.logfiles[lname] = lname
        self.addLogObserver('state.log', MockStateObserver())

        cmd = remotecommand.RemoteCommand('rmdir', {'dir':
                                                    [self.build.path_module.join('build', self.logfiles[l])
                                                     for l in self.mock_logfiles]})
        d = self.runCommand(cmd)
        # must resolve super() outside of the callback context.
        super_ = super()

        @d.addCallback
        def removeDone(cmd):
            super_.start()
        d.addErrback(self.failed)
467483
def StartExecServer():
  """"""
  sockdir = '/tmp/pyringe_%s' % os.getpid()
  if not os.path.isdir(sockdir):
    os.mkdir(sockdir)
  socket_path = ('%s/%s.execsock' %
                 (sockdir, threading.current_thread().ident))

  if os.path.exists(socket_path):
    os.remove(socket_path)

  exec_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  exec_sock.bind(socket_path)
  exec_sock.listen(5)
  shutdown = False
  while not shutdown:
    conn, _ = exec_sock.accept()

    data = conn.recv(1024)
    if data:
      if data == '__kill__':
        shutdown = True
        conn.send('__kill_ack__')
        break
      data = json.loads(data)
      try:
        conn.sendall(json.dumps(eval(data)))
      except SyntaxError:
        # Okay, so it probably wasn't an expression
        try:
          exec data  # pylint: disable=exec-used
        except:  # pylint: disable=bare-except
          # Whatever goes wrong when exec'ing this, we don't want to crash.
          # TODO: think of a way to properly tunnel exceptions, if
          # possible without introducing more magic strings.
          pass
        finally:
          conn.sendall(json.dumps(None))
  exec_sock.shutdown(socket.SHUT_RDWR)
  exec_sock.close()
  os.remove(socket_path)