Launching server

@throws ForkException
@throws SocketException
@return void
186119
public function run(): void
    {
        pcntl_async_signals(true);

        $this->makeSocket();

        [$pid, $master, $workers] = $this->spawn();

        if ($pid) {
            fclose($this->socket);
            $this->workerPids = $workers;
            $this->handleSignals();

            (new Master($workers, $this->unixConnector, $this->exchangeWorkersData))->dispatch();
        } else {
            if ($this->useConnector) {
                fclose($this->unixConnector);
            }

            (new $this->handler($this->socket, $master))->handle();
        }
    }
582500
final public function startup(object $server = null) : void
    {
        $this->process = new SWProcess(function (SWProcess $process) {
            // set process name
            if ($this->name) {
                @$process->name(sprintf('[process] %s', $this->name));
            }

            // progress notify
            Progress::started(getmypid(), $this->name);

            // start pipe reading
            $this->forked->reading();

            // trigger system startup
            $this->forked->bootstrap();

            // trigger event::program::started
            $this->action(Program::STARTED);

            // trigger user starting
            $this->starting();
        });

        // running
        $server instanceof SWServer ? $server->addProcess($this->process) : Master::watch($this->process->start());

        // flag
        $this->started = true;
    }
1300554
private function runHosted()
    {
        $nb_server = CNabuServer::findByKey($this->server_key);
        $apache_server = new CApacheHTTPServer($nb_server);

        if ($apache_server->locateApacheServer()) {
            $this->displayServerConfig($apache_server);
            $apache_server->createHostedConfiguration();
        }
    }
320002
public function start()
    {
        RequestContext::destroy();
        PoolManager::clearPools();
        CacheManager::clearPools();
        App::createServers();
        ServerManage::getServer('main')->getSwooleServer()->start();
    }
306517
def start_server
      @connect_lock.synchronize do
        begin
          raise "Adapter already set" if @adapter
          @adapter = Lock.new(@builder.build.last)
          raise "Server already set" if @server
          @server = Server.new(@adapter, @options)
          @thread = Thread.new { @server.run }
          sleep 0.1 until @server.running?
        rescue => ex
          @adapter.close if @adapter
          @adapter = nil
          @server = nil
          @thread = nil
          warn "Moneta::Shared - Failed to start server: #{ex.message}"
        end
      end
    end
111141
public function run()
    {
        //Update process state.
        self::$_status = self::STATUS_RUNNING;

        // Register shutdown function for checking errors.
        register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));

        // Set autoload root path.
        Autoloader::setRootPath($this->_autoloadRootPath);
        // Create a global event loop.
        if (!self::$globalEvent) {
            $event_loop_class = self::getEventLoopName();
            self::$globalEvent = new $event_loop_class;
            // Register a listener to be notified when server socket is ready to read.
            if ($this->_socketName) {
                if ($this->transport !== 'udp') {
                    self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
                        array($this, 'acceptConnection'));
                } else {
                    self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
                        array($this, 'acceptUdpConnection'));
                }
            }
        }


        // Reinstall signal.
        self::reinstallSignal();

        // Init Timer.
        Timer::init();

        // Try to emit onWorkerStart callback.
        if ($this->onWorkerStart) {
            try {
                call_user_func($this->onWorkerStart, $this);
            } catch (\Exception $e) {
                self::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            } catch (\Error $e) {
                self::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            }
        }


        // Main loop.
        self::$globalEvent->loop();
    }
1210997
public function start()
    {
        $this->events->dispatch(new Events\ServerLaunching($this));

        $this->running = true;

        $this->dispatchEvent('Launching', $this);

        $result = $this->swooleServer->start();

        $this->running = false;

        return $result;
    }
1275232
public function open()
    {

        $this->log('open socket connection');
        $this->socket = fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
        if ($this->socket) {
            socket_set_blocking($this->socket, 1);

            return true;
        } else {
            throw(new \Exception("{$errstr} (#{$errno})"));
        }
    }
985478
private function startWampServer()
    {
        if (! $this->serverInstance instanceof RatchetWampServer) {
            throw new \Exception("{$this->class} must be an instance of ".RatchetWampServer::class." to create a Wamp server");
        }

        // Decorate the server instance with a WampServer
        $this->serverInstance = new WampServer($this->serverInstance);

        return $this->bootWebSocketServer(true);
    }
643879
public void startServers() throws Exception {
        for (ServerFace face : getBeans(ServerFace.class)) {
            serverFaces.add(face);
            face.start();
        }
    }
691775
public function onStart(Server $server): void
    {
        $this->fire(ServerEvent::STARTED, $server);

        $this->masterPid = $masterPid = $server->master_pid;
        $rootPath        = $this->config('rootPath');
        $rootPath        = $rootPath ? " (at $rootPath)" : '';

        // save master process id to file.
        ProcessUtil::setTitle(sprintf('%s: master%s', $this->name, $rootPath));

        $this->log("The <comment>master</comment> process success started. (PID:<info>{$masterPid}</info>, pidFile: $this->pidFile)");
    }
1055980
public function run()
    {
        $this->connect();

        while (!$this->moribund) {

            $read = $this->getReadArray();

            // Suppressing warnings for stream_select() because it will raise
            // a warning if interrupted by a signal.
            $result = @stream_select(
                $read,
                $write = null,
                $except = null,
                null
            );

            if ($result === false || $result < 1) {
                continue;
            }

            // check for new connections
            if (in_array($this->socket->getRawSocket(), $read)) {
                try {
                    $newSocket = new Net_Notifier_Socket_Accept(
                        $this->socket,
                        null
                    );
                } catch (Net_Notifier_Socket_Exception $e) {
                    $this->log(
                        'Accepting client connection failed: reason: '
                        . $e->getMessage() . PHP_EOL,
                        Net_Notifier_Logger::VERBOSITY_ERRORS
                    );
                }

                $client = new Net_Notifier_WebSocket_Connection($newSocket);
                $this->clients[] = $client;
                $this->log(
                    'client connected from ' . $client->getIPAddress()
                    . PHP_EOL,
                    Net_Notifier_Logger::VERBOSITY_CLIENT
                );
            }

            // check for client data
            foreach ($this->getReadClients($read) as $client) {

                $moribund = false;

                // check if client closed connection
                $bytes = $client->getSocket()->peek(1);

                if (mb_strlen($bytes, '8bit') === 0) {
                    $this->log(
                        sprintf(
                            'client %s closed connection.' . PHP_EOL,
                            $client->getIPAddress()
                        ),
                        Net_Notifier_Logger::VERBOSITY_CLIENT
                    );

                    $moribund = true;
                }

                try {

                    if ($client->read(self::READ_BUFFER_LENGTH)) {

                        if ($client->getState() < Net_Notifier_WebSocket_Connection::STATE_CLOSING) {

                            $receivedRelayMessage = false;
                            $messages = $client->getTextMessages();
                            foreach ($messages as $message) {
                                $this->log(
                                    sprintf(
                                        'received message: "%s" from %s'
                                        . PHP_EOL,
                                        $message,
                                        $client->getIPAddress()
                                    ),
                                    Net_Notifier_Logger::VERBOSITY_MESSAGES
                                );

                                $message = json_decode($message, true);

                                if (   $message === false
                                    || !isset($message['action'])
                                ) {
                                    $this->log(
                                        '=> incorrectly formatted' . PHP_EOL,
                                        Net_Notifier_Logger::VERBOSITY_MESSAGES
                                    );

                                    $this->startCloseClient(
                                        $client,
                                        Net_Notifier_WebSocket_Connection::CLOSE_PROTOCOL_ERROR,
                                        'Incorrectly formatted message.'
                                    );

                                    break;
                                }

                                if ($message['action'] === 'shutdown') {
                                    $this->log(
                                        sprintf(
                                            'shutting down at request of %s'
                                            . PHP_EOL,
                                            $client->getIPAddress()
                                        ),
                                        Net_Notifier_Logger::VERBOSITY_MESSAGES
                                    );

                                    $this->startCloseClient(
                                        $client,
                                        Net_Notifier_WebSocket_Connection::CLOSE_NORMAL,
                                        'Received shutdown message.'
                                    );

                                    $this->moribund = true;
                                }

                                if ($message['action'] === 'listen') {
                                    $this->log(
                                        sprintf(
                                            'set %s to listen' . PHP_EOL,
                                            $client->getIPAddress()
                                        ),
                                        Net_Notifier_Logger::VERBOSITY_MESSAGES
                                    );

                                    if (!in_array($client, $this->listenClients)) {
                                        $this->listenClients[] = $client;
                                    }
                                } else {
                                    $this->relayNotification($message);
                                    $receivedRelayMessage = true;
                                }
                            }

                            if ($receivedRelayMessage) {
                                $this->startCloseClient(
                                    $client,
                                    Net_Notifier_WebSocket_Connection::CLOSE_NORMAL,
                                    'Received message for relay.'
                                );
                            }
                        }

                    } else {

                        $this->log(
                            sprintf(
                                'got a message chunk from %s' . PHP_EOL,
                                $client->getIPAddress()
                            ),
                            Net_Notifier_Logger::VERBOSITY_CLIENT
                        );

                        if ($client->getState() === Net_Notifier_WebSocket_Connection::STATE_CLOSED) {
                            $this->log(
                                sprintf(
                                    'completed close handshake from %s'
                                    . PHP_EOL,
                                    $client->getIPAddress()
                                ),
                                Net_Notifier_Logger::VERBOSITY_CLIENT
                            );
                            $moribund = true;
                        }

                    }

                } catch (Net_Notifier_WebSocket_HandshakeFailureException $e) {
                    $this->log(
                        sprintf(
                            'failed client handshake: %s' . PHP_EOL,
                            $e->getMessage()
                        ),
                        Net_Notifier_Logger::VERBOSITY_CLIENT
                    );
                }

                if ($moribund) {
                    $this->closeClient($client);
                }

            }

        }

        $this->disconnect();
    }
846943
public void run()
    {
        this.serverSocket = null;
        try
        {
            Log(Level.INFO, "Attempting to create SocketServer...");
            // If requrestedPortNumber is 0 and we have a range of ports specified, then attempt to allocate a port dynamically from that range.
            if (this.requestedPortNumber == 0 && this.portRangeMax != -1 && this.portRangeMin != -1) {
                this.serverSocket = TCPUtils.getSocketInRange(this.portRangeMin, this.portRangeMax, this.choosePortRandomly);
                if (this.serverSocket == null)
                    throw new Exception("Could not allocate port from range.");
            } else	// Attempt to use the requested port - if it's 0, the system will allocate one dynamically.
                this.serverSocket = new ServerSocket(this.requestedPortNumber);	// Use the specified port number
        }
        catch (Exception e)
        {
            SysLog(Level.SEVERE, "Failed to create SocketServer: " + e);
            this.failedToCreate = true;
            return;
        }

        SysLog(Level.INFO, "Listening for messages on port " + this.serverSocket.getLocalPort());

        while (keepRunning)
        {
            Socket socket = null;
            try
            {
                Log(Level.INFO, "Waiting for incoming message...");
                socket = this.serverSocket.accept();
                if (socket != null)
                    Log(Level.INFO, "Connected to: " + socket.getLocalAddress() + "(local), " + socket.getRemoteSocketAddress() + "(remote)");
                else
                    Log(Level.WARNING, "Accept() returns a null socket!?");
            }
            catch (SocketException e)
            {
                SysLog(Level.INFO, "Socket exception - usually caused by ServerSocket being closed under our feet (normal for stopping polling): " + e);
            }
            catch (IOException e)
            {
                SysLog(Level.SEVERE, "Failed to accept socket request: " + e);
            }

            if (socket != null)
            {
                this.connection_count++;
                Runnable connectionHandler = new TCPConnectionHandler(socket, this, this.logname + ":S#" + this.connection_count);
                new Thread(connectionHandler).start();
            }
        }

        if (this.serverSocket != null)
        {
            try
            {
                Log(Level.INFO, "Closing server socket...");
                this.serverSocket.close();
                Log(Level.INFO, "...closed okay.");
            }
            catch (IOException e)
            {
                Log(Level.SEVERE, "Something went wrong closing server socket: " + e);
            }
        }
    }
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);
                        }
                    });
                }
            }
        });
    }
340574
public function open()
    {
        $this->socket = stream_socket_client('tcp://'.$this->address, $errc, $errs, STREAM_CLIENT_CONNECT);

        if (!$this->socket) {
            throw new HSException('Connection to '.$this->address.' failed');
        }
    }
1352646
public function start()
    {
        if (!$this->open()) {
            return false;
        }

        foreach ($this->_servers as $s) {
            // Servername, port, sharedsecret, timeout, retries
            if (!$this->putServer($s[0], $s[1], $s[2], $s[3], $s[4])) {
                return false;
            }
        }

        if (!empty($this->_configfile)) {
            if (!$this->putConfigfile($this->_configfile)) {
                return false;
            }
        }

        $this->createRequest();
        $this->putStandardAttributes();
        $this->putAuthAttributes();
        return true;
    }
1195543
public function run() {

        if(!$this->server) {

            try {

                // initialize socket server
                $this->server = new AppServer($this->config->socket->host, $this->config->socket->port);

                // create application with dependencies
                $app = new Sonar(
                    new StorageService($this->config->storage),
                    new QueueService($this->config->beanstalk),
                    new GeoService(),
                    new CacheService()
                );
                $this->server->route('/sonar', $app, ['*']);
            }
            catch(QueueServiceException $e) {
                throw new AppServiceException($e->getMessage());
            }
            catch(ConnectionException $e) {
                throw new SocketServiceException($e->getMessage());
            }
            catch(StorageServiceException $e) {
                throw new AppServiceException($e->getMessage());
            }
            catch(CacheServiceException $e) {
                throw new AppServiceException($e->getMessage());
            }

        }

        if(isset($this->config->storage) === false) {
            throw new AppServiceException('There is no option `storage` in your configurations');
        }

        $this->server->run();
    }