Enable socket events
@return void
432541
public function enable()
    {
        if ($this->enabled) {
            return;
        }
        if (!$this->fd) {
            return;
        }
        $this->enabled = true;
        if ($this->ev === null) {
            if ($this->eventLoop === null) {
                $this->eventLoop = EventLoop::$instance;
            }
            $this->ev = $this->eventLoop->listener(
                [$this, 'onAcceptEv'],
                null,
                \EventListener::OPT_CLOSE_ON_FREE | \EventListener::OPT_REUSEABLE,
                -1,
                $this->fd
            );
            $this->onBound();
        } else {
            $this->ev->enable();
        }
    }
423911
function broadcast(event, data) {
	HttpSockets.forEach(
		function(socket) {
			socket.emit(event, data);
		});
}
227866
private function onWritable()
    {
        $bytesWritten = @\fwrite($this->socket, $this->writeBuffer);

        if ($bytesWritten === false) {
            $this->close();
            return;
        }

        if ($bytesWritten === 0) {
            return;
        }

        $this->timeoutCache->renew($this->id);

        if ($bytesWritten !== \strlen($this->writeBuffer)) {
            $this->writeBuffer = \substr($this->writeBuffer, $bytesWritten);
            return;
        }

        $this->writeBuffer = "";

        Loop::disable($this->writeWatcher);
        $deferred = $this->writeDeferred;
        $this->writeDeferred = null;
        $deferred->resolve();
    }
486929
private function tryConnect(): void
    {
        $config = $this->getConfig();

        $pdoConfig = [
          PDO::ATTR_EMULATE_PREPARES => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_PERSISTENT => $config['persistent'] ?? true,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];

        if (isset($config['adapter_options'])) {
            foreach ($config['adapter_options'] as $key => $value) {
                $pdoConfig[$key] = $value;
            }
        }

        if (!isset($config['socket'])) {
            // not a socket
            $port = $config['port'] ?? 5432;

            $this->pdo = new PDO("pgsql:host={$config['host']};port={$port};dbname={$config['database']}", $config['username'], $config['password'], $pdoConfig);
        } else {
            // the case with unix_socket
            $this->pdo = new PDO("pgsql:dbname={$config['database']}", $config['username'], $config['password'], $pdoConfig);
        }

        if (isset($config['schema'])) {
            $schemaSql = 'SET search_path TO ' . $config['schema'];
            $this->pdo->exec($schemaSql);
            Log::sql($schemaSql);
        }
    }
864685
private function registerEventListeners()
    {
        $listeners = $this->getListeners();
        foreach ($listeners as $listenerKey => $listenerValues) {
            foreach ($listenerValues as $listenerValue) {
                \Event::listen($listenerKey,
                    $listenerValue
                );
            }
        }
    }
1247974
public function handleEvent()
    {
        while ($this->socket !== null)
        {
            $events = $this->socket->getSockOpt(ZMQ::SOCKOPT_EVENTS);

            $hasEvents = ($events & ZMQ::POLL_IN) || ($events & ZMQ::POLL_OUT && $this->buffer->listening);
            if (!$hasEvents)
            {
                break;
            }

            if ($events & ZMQ::POLL_IN)
            {
                $this->handleReadEvent();
            }

            if ($events & ZMQ::POLL_OUT && $this->buffer->listening)
            {
                $this->buffer->handleWriteEvent();
            }
        }
    }
1312234
public function events()
    {
        return [
            Server::ON_CONNECT => 'onConnect',
            Server::ON_MESSAGE => 'onMessage',
            Server::ON_CLOSE => 'onClose',
            Server::ON_ERROR => 'onError',
            Server::ON_BAD_PACKET => 'onBadPacket',
            Server::ON_BUFFER_FULL => 'onBufferFull',
            Server::ON_BUFFER_DRAIN => 'onBufferDrain',
            Server::ON_SSL_HANDSHAKED => 'onSSLHandShaked',
            Server::ON_UDP_PACKET => 'onUdpPacket',
            Server::ON_START_ACCEPT => 'onStartAccept',
            Server::ON_STOP_ACCEPT => 'onStopAccept',
        ];
    }
764330
public function onRead()
    {
        start:
        if ($this->type === 'udp') {
            $this->onUdpPacket($this->read($this->getInputLength()));
            return;
        }
        if ($this->state === self::STATE_ROOT) {
            if (false === ($hdr = $this->readExact(2))) {
                return; // not enough data
            }
            $this->pctSize = Binary::bytes2int($hdr);
            $this->setWatermark($this->pctSize);
            $this->state = self::STATE_PACKET;
        }
        if ($this->state === self::STATE_PACKET) {
            if (false === ($pct = $this->readExact($this->pctSize))) {
                return; // not enough data
            }
            $this->state = self::STATE_ROOT;
            $this->setWatermark(2);
            $this->onUdpPacket($pct);
        }
        goto start;
    }
295737
public function open()
    {
        $cString = $this->scheme . $this->host . ':' . $this->port;
        $this->context = stream_context_create();
        $errno = 0;
        $errstr = '';
        $this->socket = @stream_socket_client(
            $cString,
            $errno,
            $errstr,
            $this->cTimeout,
            STREAM_CLIENT_CONNECT,
            $this->context
        );
        if ($this->socket === false) {
            throw new ClientException('Error connecting to ami: ' . $errstr);
        }
        $msg = new LoginAction($this->user, $this->pass, $this->eventMask);
        $asteriskId = @stream_get_line($this->socket, 1024, Message::EOL);
        if (strstr($asteriskId, 'Asterisk') === false) {
            throw new ClientException(
                "Unknown peer. Is this an ami?: $asteriskId"
            );
        }
        $response = $this->send($msg);
        if (!$response->isSuccess()) {
            throw new ClientException(
                'Could not connect: ' . $response->getMessage()
            );
        }
        @stream_set_blocking($this->socket, 0);
        $this->currentProcessingMessage = '';
        $this->logger->debug('Logged in successfully to ami.');
    }
1239469
protected function connect(): void
    {
        $this->connection = @\stream_socket_client( // @ is escalated to exception
            ($this->secure === 'ssl' ? 'ssl://' : '') . $this->host . ':' . $this->port,
            $errno, $error, $this->timeout, STREAM_CLIENT_CONNECT, $this->context
        );
        if (!$this->connection) {
            throw new SmtpException($error ?: error_get_last()['message'], $errno);
        }
        \stream_set_timeout($this->connection, $this->timeout, 0);
        $this->read(); // greeting

        $this->write("EHLO {$this->clientHost}");
        $ehloResponse = $this->read();
        if ((int) $ehloResponse !== 250) {
            $this->write("HELO {$this->clientHost}", 250);
        }

        if ($this->secure === 'tls') {
            $this->write('STARTTLS', 220);
            if (!\stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new SmtpException('Unable to connect via TLS.');
            }
            $this->write("EHLO {$this->clientHost}", 250);
        }

        $password = $this->getPassword();
        if ($this->username !== '' && $password !== '') {
            $authMechanisms = [];
            if (\preg_match('~^250[ -]AUTH (.*)$~im', $ehloResponse, $matches)) {
                $authMechanisms = \explode(' ', \trim($matches[1]));
            }

            if (\in_array('PLAIN', $authMechanisms, true)) {
                $credentials = $this->username . "\0" . $this->username . "\0" . $password;
                $this->write('AUTH PLAIN ' . \base64_encode($credentials), 235, 'PLAIN credentials');
            } else {
                $this->write('AUTH LOGIN', 334);
                $this->write(\base64_encode($this->username), 334, 'username');
                $this->write(\base64_encode($password), 235, 'password');
            }
        }
    }
1110766
private function establishSocketConnection()
    {
        $host = $this->params['host'];
        if (!empty($this->params['protocol'])) {
            $host = $this->params['protocol'].'://'.$host;
        }
        $timeout = 15;
        if (!empty($this->params['timeout'])) {
            $timeout = $this->params['timeout'];
        }
        $options = [];
        if (!empty($this->params['sourceIp'])) {
            $options['socket']['bindto'] = $this->params['sourceIp'].':0';
        }

        if (isset($this->params['stream_context_options'])) {
            $options = array_merge($options, $this->params['stream_context_options']);
        }
        $streamContext = stream_context_create($options);
        $this->stream = @stream_socket_client($host.':'.$this->params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext);
        if (false === $this->stream) {
            throw new Swift_TransportException(
                'Connection could not be established with host '.$this->params['host'].
                ' ['.$errstr.' #'.$errno.']'
                );
        }
        if (!empty($this->params['blocking'])) {
            stream_set_blocking($this->stream, 1);
        } else {
            stream_set_blocking($this->stream, 0);
        }
        stream_set_timeout($this->stream, $timeout);
        $this->in = &$this->stream;
        $this->out = &$this->stream;
    }
1178214
public function start() {

        // we're activating!
        $this->is_active = true;

        $this->setup();

        foreach ( $this->workers as $name => $worker ) {

            $this->workers->start($name);

        }

        $this->becomeSupervisor();

        // start listening on socket
        try {

            $this->socket->listen();

        } catch (SocketException $e) {

            // something did wrong on socket...
            $this->logger->error($e->getMessage());
            $this->stop();
            $this->end(0);

        }

        // loop closed; if I'm the supervisor, I should clean everything
        if ( $this->is_supervisor && $this->is_active ) {
            $this->stop();
            $this->end(0);
        }

    }
764986
public function start()
    {
        $this->_socket_http = socket_create(AF_INET, SOCK_STREAM, IPPROTO_IP);
        if (!$this->_socket_http) {
            throw new Exception("Unable to create socket\n");
        }

        if (!socket_bind($this->_socket_http, self::SERVER_IP, self::LISTENING_PORT)) {
            throw new Exception('Could not bind address and port');
        }

        // Start listening for connections
        if (!socket_listen($this->_socket_http)) {
            throw new Exception('Could not listen to main socket!');
        }

        while (true) {
            // Setup clients listen socket for reading
            $this->read = $this->checkSocket($this->_socket_http);

            // Set up a blocking call to socket_select()
            $this->ready = socket_select($this->read, $this->write, $this->expect, null);

            if ($this->ready === false) {
                $this->getError();
            }

            // if there a no clients we don't need to write
            if (!$this->checkClient() || empty($this->client)) {
                continue;
            }

            // init the Execute phase
            $this->execute();

        } // end while

        // Close the master sockets
        $this->close($this->_socket_http);
    }
229304
protected function __bindEvents()
    {
        $server = $this->swoolePort ?? $this->swooleServer;

        $server->on('packet', function(\swoole_server $server, $data, $clientInfo){
            try{
                $this->trigger('packet', [
                    'server'        => $this,
                    'data'          => $data,
                    'clientInfo'    => $clientInfo,
                ], $this, PacketEventParam::class);
            }
            catch(\Throwable $ex)
            {
                App::getBean('ErrorLog')->onException($ex);
            }
        });
        
    }
782630
public function selectAndProcess(): void
    {
        $read = $this->resources;
        $unused_write = null;
        $unsued_exception = null;

        stream_select(
            $read,
            $unused_write,
            $unused_exception,
            $this->options['timeout_select'],
            $this->options['timeout_select_microsec']
        );

        foreach ($read as $socket) {
            if ($socket == $this->socket->getResource()) {
                $this->processMasterSocket();
            } else {
                $this->processClientSocket($socket);
            }
        }
    }
319148
public function enable()
    {
        if ($this->enabled) {
            return;
        }
        if (!$this->fd) {
            return;
        }
        $this->enabled = true;

        if ($this->ev === null) {
            if ($this->eventLoop === null) {
                // @TODO нужно перенести куда-то выше, не годиться тут инициировать
                $this->eventLoop = EventLoop::$instance;
            }

            $this->ev = $this->eventLoop->event($this->fd, \Event::READ | \Event::PERSIST, [$this, 'onReadUdp']);
            $this->onBound();
        } else {
            $this->onAcceptEv();
        }
        $this->ev->add();
    }
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})"));
        }
    }