This is the main server loop.  This code is responsible for adding connections and triggering hooks.

@throws \Navarr\Socket\Exception\SocketException

@return bool Whether or not to shutdown the server
169846
protected function loopOnce()
    {
        // Get all the Sockets we should be reading from
        $read = array_merge([$this->masterSocket], $this->clients);

        // Set up a block call to socket_select
        $write = null;
        $except = null;
        $ret = Socket::select($read, $write, $except, $this->timeout);
        if (!is_null($this->timeout) && $ret == 0) {
            if ($this->triggerHooks(self::HOOK_TIMEOUT, $this->masterSocket) === false) {
                // This only happens when a hook tells the server to shut itself down.
                return false;
            }
        }

        // If there is a new connection, add it
        if (in_array($this->masterSocket, $read)) {
            unset($read[array_search($this->masterSocket, $read)]);
            $socket = $this->masterSocket->accept();
            $this->clients[] = $socket;

            if ($this->triggerHooks(self::HOOK_CONNECT, $socket) === false) {
                // This only happens when a hook tells the server to shut itself down.
                return false;
            }
            unset($socket);
        }

        // Check for input from each client
        foreach ($read as $client) {
            $input = $this->read($client);

            if ($input === '') {
                if ($this->disconnect($client) === false) {
                    // This only happens when a hook tells the server to shut itself down.
                    return false;
                }
            } else {
                if ($this->triggerHooks(self::HOOK_INPUT, $client, $input) === false) {
                    // This only happens when a hook tells the server to shut itself down.
                    return false;
                }
            }
            unset($input);
        }

        // Unset the variables we were holding on to
        unset($read);
        unset($write);
        unset($except);

        // Tells self::run to Continue the Loop
        return true;
    }
977642
public function execute()
    {
        // loop through the open client connections
        foreach ($this->client as $key => $client) {
            // if the client connection doesn exist in the current read iteration
            if (!in_array($client['sock'], $this->read)) {
                // Close the socket
                $this->close($client['sock']);
                // flag for garbage collection
                unset($this->client[$key]);
            }

            // get the input from the client
            $input = socket_read($client['sock'], 1024);


            // Zero length string meaning disconnected
            if ($input == null) {
                unset($this->client[$key]);
            }
            $n = trim($input);

            switch (true) {
                // kill switch for telnet
                case $n === 'exit':
                    $this->close($client['sock']);
                    break;

                default:
                    // here is where it get interesting we will need a Handler who responds
                    socket_write($client['sock'], $this->getResponse($input));
                    break;
            }
        }
    }
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();
    }
1238772
private function connecting() : void
    {
        $this->connected = false;
        $this->closing
            ? $this->closed()->resolve()
            : $this->client = Socket::connect($this->endpoint, $this->events)
        ;
    }
256208
public function close() {

		// Make sure nothing unexpected happens
		try {
		
			// Check that a connection exists first
                	if( isset( $this->socket ) ) {

				// Close the socket
                        	fclose( $this->socket );

				// Unset the socket property
                        	unset($this->socket);

				// The connection is no longer established
				$this->established = false;
                	}

		} catch (Exception $e) {

			throw new MPDConnectionException( 'Disconnection failed: '.$e->getMessage(), self::MPD_DISCONNECTION_FAILED );		
		}

		// We'll assume it was successful
                return true;
        }
1178526
public function disconnect()
    {
        if (!$this->connected || !$this->server || ($this->mode ==  "mysql" && $this->server->connect_error)) {
            return false;
        }

        $result = false;

        switch ($this->mode) {

            case "mysql":
            case "sqlite":
                $result = $this->server->close();
                break;

            case "postgres":
            case "redshift":
                $result = pg_close($this->server);
                break;

            case "odbc":
                odbc_close($this->server);
                $result = true;
                break;

            case "mssql":
                $result = mssql_close($this->server);
                break;

            case "mssqlsrv":
                $result = sqlsrv_close($this->server);
                break;
        }

        # If the disconnect was successful, set class property to reflect it
        if ($result) {
            $this->connected = false;
        }

        return $result;
    }
525472
function _close()
	{
		if ($this->_connectionID) $this->_connectionID->Close();
		$this->_connectionID = false;
		return true;
	}
1215158
public function connected()
    {
        if (is_resource($this->smtp_conn)) {
            $sock_status = stream_get_meta_data($this->smtp_conn);
            if ($sock_status['eof']) {
                // The socket is valid but we are not connected
                $this->edebug(
                    'SMTP NOTICE: EOF caught while checking if connected',
                    self::DEBUG_CLIENT
                );
                $this->close();

                return false;
            }

            return true; // everything looks good
        }

        return false;
    }
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();
    }
27406
public function disconnect()
    {
        if (!is_resource($this->fp)) {
            return $this->raiseError('not connected');
        }

        @fclose($this->fp);
        $this->fp = null;

        return true;
    }
554438
public function disconnect()
    {
        if (!is_resource($this->connection)) {
            $this->connected = false;

            return true;
        }
        $this->connected = !fclose($this->connection);

        if (!$this->connected) {
            $this->connection = null;
        }

        return !$this->connected;
    }
572970
protected function shouldBeConnected()
    {
        // If we lost the connection, first let's try and reconnect
        if (!$this->isConnected()) {
            try {
                $this->switchNodeIfNeeded();
            } catch (ConnectionException $e) {
                throw new ConnectionException('Not connected. ' . $e->getMessage(), 0, $e);
            }
        }
    }
939994
public function close()
    {
        if (!$this->connected) {
            return false;
        }

        $this->connected = false;
        fclose($this->socket);

        return true;
    }
755988
public function stop()
    {
        if (!$this->started) {
            throw new Exception\ConnectionException('Client is not started');
        }

        if ($this->browserAutoruned) {
            $this->con->stop();
        }

        $this->started = false;
    }
761398
public function run()
    {

        // register a shutdown function
        register_shutdown_function(array($this, 'shutdown'));

        // register the default autoloader
        require SERVER_AUTOLOADER;

        try {
            // iterate over all structures and generate them
            foreach ($this->structures as $structure) {
                $this->generator->create($structure);
            }

        } catch (\Exception $e) {
            $this->log(LogLevel::ERROR, $e->__toString());
        }
    }
190429
public function run()
    {
        $this->log("Server listening on {$this->host}:{$this->port}");
        $this->socket->listen($this->port, $this->host);
        $this->loop->run();
    }
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;
    }