Called when the connection is handshaked (at low-level), and peer is ready to recv. data
@return void
426238
public function onReady()
    {
        $this->createXMLStream();
        $this->startXMLStream();
        $this->keepaliveTimer = setTimeout(function ($timer) {
            $this->ping();
        }, 1e6 * 30);
    }
1254325
public function onReady()
    {
        $this->ptr =& $this->result;
        if (!isset($this->password)) {
            if (isset($this->pool->config->select->value)) {
                $this->select($this->pool->config->select->value);
            }
            parent::onReady();
            $this->setWatermark(null, $this->pool->maxAllowedPacket + 2);
            return;
        }
        $this->sendCommand('AUTH', [$this->password], function () {
            if ($this->result !== 'OK') {
                $this->log('Auth. error: ' . json_encode($this->result));
                $this->finish();
            }
            if (isset($this->pool->config->select->value)) {
                $this->select($this->pool->config->select->value);
            }
            parent::onReady();
            $this->setWatermark(null, $this->pool->maxAllowedPacket + 2);
        });
    }
1110678
private function connect()
    {
        $this->conn = parent::getConn();
        $this->read = $this->conn->prepare($this->sql);
        $this->read->setFetchMode(\PDO::FETCH_ASSOC);
    }
607953
public function onReady()
    {
        if (mb_orig_strlen($this->path) && !mb_orig_strlen($this->dbname)) {
            $this->dbname = $this->path;
        }
    }
691046
public function onRead()
    {
        if ($this->state === self::STATE_PREHANDSHAKE) {
            if ($this->getInputLength() < 8) {
                return;
            }
            $this->key = $this->readUnlimited();
            $this->handshake();
        }
        if ($this->state === self::STATE_HANDSHAKED) {
            while (($buflen = $this->getInputLength()) >= 2) {
                $hdr = $this->look(10);
                $frametype = ord(mb_orig_substr($hdr, 0, 1));
                if (($frametype & 0x80) === 0x80) {
                    $len = 0;
                    $i = 0;
                    do {
                        if ($buflen < $i + 1) {
                            // not enough data yet
                            return;
                        }
                        $b = ord(mb_orig_substr($hdr, ++$i, 1));
                        $n = $b & 0x7F;
                        $len *= 0x80;
                        $len += $n;
                    } while ($b > 0x80);

                    if ($this->pool->maxAllowedPacket <= $len) {
                        // Too big packet
                        $this->finish();
                        return;
                    }

                    if ($buflen < $len + $i + 1) {
                        // not enough data yet
                        return;
                    }
                    $this->drain($i + 1);
                    $this->onFrame($this->read($len), 'BINARY');
                } else {
                    if (($p = $this->search("\xFF")) !== false) {
                        if ($this->pool->maxAllowedPacket <= $p - 1) {
                            // Too big packet
                            $this->finish();
                            return;
                        }
                        $this->drain(1);
                        $data = $this->read($p);
                        $this->drain(1);
                        $this->onFrame($data, 'STRING');
                    } else {
                        if ($this->pool->maxAllowedPacket < $buflen - 1) {
                            // Too big packet
                            $this->finish();
                            return;
                        }
                        // not enough data yet
                        return;
                    }
                }
            }
        }
    }
535055
public function recv()
	{
		// receive a message from the socket
		$message = $this->ws->receive();

		// is the message is empty?
		if (empty($message))
		{
			return;
		}

		// decode the message (json_decode + error checking)
		$message = $this->decodeMessage($message);

		// injest and route the message
		$this->injest($message);
	}
455196
public function onRead()
    {
        if ($this->state === self::STATE_BODY) {
            goto body;
        }
        if ($this->reqType === null) {
            if ($this->requests->isEmpty()) {
                $this->finish();
                return;
            }
            $this->reqType = $this->requests->shift();
        }
        while (($line = $this->readLine()) !== null) {
            if ($line !== '') {
                if ($this->rawHeaders !== null) {
                    $this->rawHeaders[] = $line;
                }
            } else {
                if (isset($this->headers['HTTP_CONTENT_LENGTH'])) {
                    $this->contentLength = (int)$this->headers['HTTP_CONTENT_LENGTH'];
                } else {
                    $this->contentLength = -1;
                }
                if (isset($this->headers['HTTP_TRANSFER_ENCODING'])) {
                    $e = explode(', ', strtolower($this->headers['HTTP_TRANSFER_ENCODING']));
                    $this->chunked = in_array('chunked', $e, true);
                } else {
                    $this->chunked = false;
                }
                if (isset($this->headers['HTTP_CONNECTION'])) {
                    $e = explode(', ', strtolower($this->headers['HTTP_CONNECTION']));
                    $this->keepalive = in_array('keep-alive', $e, true);
                }
                if (isset($this->headers['HTTP_CONTENT_TYPE'])) {
                    parse_str('type=' . strtr($this->headers['HTTP_CONTENT_TYPE'], [';' => '&', ' ' => '']), $p);
                    $this->contentType = $p['type'];
                    if (isset($p['charset'])) {
                        $this->charset = strtolower($p['charset']);
                    }
                }
                if ($this->contentLength === -1 && !$this->chunked && !$this->keepalive) {
                    $this->eofTerminated = true;
                }
                if ($this->reqType === 'HEAD') {
                    $this->requestFinished();
                } else {
                    $this->state = self::STATE_BODY;
                }
                break;
            }
            if ($this->state === self::STATE_ROOT) {
                $this->headers['STATUS'] = $line;
                $e = explode(' ', $this->headers['STATUS']);
                $this->responseCode = isset($e[1]) ? (int)$e[1] : 0;
                $this->state = self::STATE_HEADERS;
            } elseif ($this->state === self::STATE_HEADERS) {
                $e = explode(': ', $line);

                if (isset($e[1])) {
                    $k = 'HTTP_' . strtoupper(strtr($e[0], Generic::$htr));
                    if ($k === 'HTTP_SET_COOKIE') {
                        parse_str(strtr($e[1], [';' => '&', ' ' => '']), $p);
                        if (sizeof($p)) {
                            $this->cookie[$k = key($p)] =& $p;
                            $p['value'] = $p[$k];
                            unset($p[$k], $p);
                        }
                    }
                    if (isset($this->headers[$k])) {
                        if (is_array($this->headers[$k])) {
                            $this->headers[$k][] = $e[1];
                        } else {
                            $this->headers[$k] = [$this->headers[$k], $e[1]];
                        }
                    } else {
                        $this->headers[$k] = $e[1];
                    }
                }
            }
        }
        if ($this->state !== self::STATE_BODY) {
            return; // not enough data yet
        }
        body:
        if ($this->eofTerminated) {
            $body = $this->readUnlimited();
            if ($this->chunkcb) {
                $func = $this->chunkcb;
                $func($body);
            }
            $this->body .= $body;
            return;
        }
        if ($this->chunked) {
            chunk:
            if ($this->curChunkSize === null) { // outside of chunk
                $l = $this->readLine();
                if ($l === '') { // skip empty line
                    goto chunk;
                }
                if ($l === null) {
                    return; // not enough data yet
                }
                if (!ctype_xdigit($l)) {
                    $this->protocolError = __LINE__;
                    $this->finish(); // protocol error
                    return;
                }
                $this->curChunkSize = hexdec($l);
            }
            if ($this->curChunkSize !== null) {
                if ($this->curChunkSize === 0) {
                    if ($this->readLine() === '') {
                        $this->requestFinished();
                        return;
                    } else { // protocol error
                        $this->protocolError = __LINE__;
                        $this->finish();
                        return;
                    }
                }
                $n = $this->curChunkSize - mb_orig_strlen($this->curChunk);
                $this->curChunk .= $this->read($n);
                if ($this->curChunkSize <= mb_orig_strlen($this->curChunk)) {
                    if ($this->chunkcb) {
                        $func = $this->chunkcb;
                        $func($this->curChunk);
                    }
                    $this->body .= $this->curChunk;
                    $this->curChunkSize = null;
                    $this->curChunk = '';
                    goto chunk;
                }
            }
        } else {
            $body = $this->read($this->contentLength - mb_orig_strlen($this->body));
            if ($this->chunkcb) {
                $func = $this->chunkcb;
                $func($body);
            }
            $this->body .= $body;
            if (($this->contentLength !== -1) && (mb_orig_strlen($this->body) >= $this->contentLength)) {
                $this->requestFinished();
            }
        }
    }
25705
public function onHandshakePacket(HandshakePacket $packet)
    {
        //only allow protocol 47 to connect (1.8+) TODO can probably allow greater range, needs testing
        if($packet->getProtocolVersion() != 47) {
            $this->disconnectClient((new DisconnectPacket())->setReason('Invalid Minecraft Version, use 1.8+'));
        }

        //move to the next stage as defined in the packet (STATUS or LOGIN)
        $this->setStage($packet->getNextStage());
    }
771554
public function onConfigUpdated()
    {
        if ($this->xmppclient) {
            $this->xmppclient->config = $this->config;
            $this->xmppclient->onConfigUpdated();
        }
    }
1181056
protected function processMasterSocket(): void
    {
        $new = null;

        try {
            $new = $this->socket->accept();
        } catch (Exception $e) {
            $this->logger->error('Socket error: {exception}', [
                'exception' => $e,
            ]);
            return;
        }

        $connection = $this->createConnection($new);
        $this->server->notify(Server::EVENT_SOCKET_CONNECT, [$new, $connection]);
    }
546647
def onConnect(self, request):
        
        logger.debug("Connection opened ({peer})".format(peer=self.peer))

        self.storage = {}
        self._client_id = str(uuid1())
1049772
public function onRead()
    {
        start:
        if ($this->state === static::STATE_HEADER) {
            $l = $this->getInputLength();
            if ($l < 2) {
                return;
            }
            $hdr = $this->look(2);
            $fb = Binary::getbitmap(ord($hdr));
            $fin = (bool)$fb{0};
            $opCode = bindec(substr($fb, 4, 4));

            if (isset($this->opCodes[$opCode])) {
                $this->type = $this->opCodes[$opCode];
            } else {
                $this->log('opCode: ' . $opCode . ': unknown frame type');
                $this->finish();
                return;
            }
            $sb = ord(mb_orig_substr($hdr, 1));
            $sbm = Binary::getbitmap($sb);
            $this->isMasked = (bool)$sbm{0};
            $payloadLength = $sb & 127;

            if ($payloadLength <= 125) {
                $this->drain(2);
                $this->pctLength = $payloadLength;
            } elseif ($payloadLength === 126) {
                if ($l < 4) {
                    return;
                }
                $this->drain(2);
                $this->pctLength = Binary::b2i($this->read(2));
            } elseif ($payloadLength === 127) {
                if ($l < 10) {
                    return;
                }
                $this->drain(2);
                $this->pctLength = Binary::b2i($this->read(8));
            }

            if ($this->pool->maxAllowedPacket < $this->pctLength) {
                Daemon::$process->log('max-allowed-packet (' . $this->pool->config->maxallowedpacket->getHumanValue() . ') exceed, aborting connection');
                $this->finish();
                return;
            }
            $this->setWatermark($this->pctLength + ($this->isMasked ? 4 : 0));
            $this->state = static::STATE_DATA;
        }

        if ($this->state === static::STATE_DATA) {
            if ($this->getInputLength() < $this->pctLength + ($this->isMasked ? 4 : 0)) {
                return;
            }
            $this->state = static::STATE_HEADER;
            $this->setWatermark(2);
            if ($this->isMasked) {
                $this->trigger('frame', static::mask($this->read(4), $this->read($this->pctLength)));
            } else {
                $this->trigger('frame', $this->read($this->pctLength));
            }
        }
        if ($this->state === static::STATE_STANDBY) {
            while (($line = $this->readLine()) !== null) {
                $line = trim($line);
                if ($line === '') {
                    $expectedKey = base64_encode(pack('H*', sha1($this->key . static::GUID)));
                    if (isset($this->headers['HTTP_SEC_WEBSOCKET_ACCEPT']) && $expectedKey === $this->headers['HTTP_SEC_WEBSOCKET_ACCEPT']) {
                        $this->state = static::STATE_HEADER;
                        if ($this->onConnected) {
                            $this->connected = true;
                            $this->onConnected->executeAll($this);
                            $this->onConnected = null;
                        }
                        $this->trigger('connected');
                        goto start;
                    } else {
                        Daemon::$process->log(__METHOD__ . ': Handshake failed. Connection to ' . $this->url . ' failed.');
                        $this->finish();
                    }
                } else {
                    $e = explode(': ', $line);
                    if (isset($e[1])) {
                        $this->headers['HTTP_' . strtoupper(strtr($e[0], ['-' => '_']))] = $e[1];
                    }
                }
            }
            return;
        }
        goto start;
    }
177786
public function onReady()
    {
        $appInstance = $this; // a reference to this application instance for ExampleWebSocketRoute
        \PHPDaemon\Servers\WebSocket\Pool::getInstance()->addRoute('ExamplePubSub',
            function ($client) use ($appInstance) {
                return new ExamplePubSubWebSocketRoute($client, $appInstance);
            });
        $this->sql = \PHPDaemon\Clients\MySQL\Pool::getInstance();
        $this->pubsub = new \PHPDaemon\PubSub\PubSub();
        $this->pubsub->addEvent('usersNum', \PHPDaemon\PubSub\PubSubEvent::init()
            ->onActivation(function ($pubsub) use ($appInstance) {
                \PHPDaemon\Core\Daemon::log('onActivation');
                if (isset($pubsub->event)) {
                    \PHPDaemon\Core\Timer::setTimeout($pubsub->event, 0);
                    return;
                }
                $pubsub->event = setTimeout(function ($timer) use ($pubsub, $appInstance) {
                    $appInstance->sql->getConnection(function ($sql) use ($pubsub) {
                        if (!$sql->connected) {
                            return;
                        }
                        $sql->query('SELECT COUNT(*) `num` FROM `dle_users`', function ($sql, $success) use ($pubsub) {
                            $pubsub->pub(sizeof($sql->resultRows) ? $sql->resultRows[0]['num'] : 'null');
                        });
                    });
                    $timer->timeout(5e6); // 5 seconds
                }, 0);
            })
            ->onDeactivation(function ($pubsub) {
                if (isset($pubsub->event)) {
                    \PHPDaemon\Core\Timer::cancelTimeout($pubsub->event);
                }
            })
        );
    }
1223400
protected function disconnect()
    {
        // Initiate connection close. The WebSockets RFC recomends against
        // clients initiating the close handshake but we want to ensure the
        // connection is closed as soon as possible.
        $this->connection->startClose(
            Net_Notifier_WebSocket_Connection::CLOSE_GOING_AWAY,
            'Client sent message.'
        );

        // read server close frame
        $state = $this->connection->getState();

        $sec  = intval($this->timeout / 1000);
        $usec = ($this->timeout % 1000) * 1000;

        while ($state < Net_Notifier_WebSocket_Connection::STATE_CLOSED) {
            $read = array($this->socket->getRawSocket());

            $result = stream_select(
                $read,
                $write = null,
                $except = null,
                $sec,
                $usec
            );

            if ($result === 1) {
                $this->connection->read(self::READ_BUFFER_LENGTH);
            } else {
                // read timed out, just close the connection
                $this->connection->close();
            }

            $state = $this->connection->getState();
        }

        $this->connection = null;
    }
1156
public function syn()
  {
    if(!isset($this->options["host"]) || empty($this->options["host"])) $this->options["host"] = $this->default_host;
    if(!isset($this->options["port"]) || empty($this->options["port"])) $this->options["port"] = $this->default_port;

    $this->initTransport($this->options, "TeamSpeak3_Transport_UDP");
    $this->transport->setAdapter($this);

    TeamSpeak3_Helper_Profiler::init(spl_object_hash($this));

    $this->getTransport()->send(TeamSpeak3_Helper_String::fromHex(33));

    if(!preg_match_all("/,?(\d+)#([0-9a-zA-Z\._-]+),?/", $this->getTransport()->read(96), $matches) || !isset($matches[1]) || !isset($matches[2]))
    {
      throw new TeamSpeak3_Adapter_Update_Exception("invalid reply from the server");
    }

    $this->build_datetimes = $matches[1];
    $this->version_strings = $matches[2];

    TeamSpeak3_Helper_Signal::getInstance()->emit("updateConnected", $this);
  }
1180485
protected final void setHandshakeComplete() {
        synchronized (this) {
            handshakeComplete = true;
        }

        ProxyIoSession proxyIoSession = getProxyIoSession();
        proxyIoSession.getConnector()
                .fireConnected(proxyIoSession.getSession())
                .awaitUninterruptibly();

        LOGGER.debug("  handshake completed");

        // Connected OK
        try {
            proxyIoSession.getEventQueue().flushPendingSessionEvents();
            flushPendingWriteRequests();
        } catch (Exception ex) {
            LOGGER.error("Unable to flush pending write requests", ex);
        }
    }
536998
public function onReady()
    {
        $this->redis = \PHPDaemon\Clients\Redis\Pool::getInstance();

        $this->redis->hmset('myset', 'field1', 'value1', 'field2', 'value2', 'field3', 'value3', 'field4', 'value4',
            'field5', 'value5', function ($redis) {
                $this->redis->hgetall('myset', function ($redis) {
                    D('TEST 1: HGETALL');
                    foreach ($redis as $key => $value) {
                        D($key . ' - ' . $value);
                    }
                    D($redis->assoc);
                });

                $this->redis->hmget('myset', 'field2', 'field4', function ($redis) {
                    D('TEST 2: HMGET');
                    foreach ($redis as $key => $value) {
                        D($key . ' - ' . $value);
                    }
                    D($redis->assoc);
                });
            });

        $this->redis->zadd('myzset', 100, 'one', 150, 'two', 325, 'three', function ($redis) {
            $this->redis->zrange('myzset', 0, -1, function ($redis) {
                D('TEST 3: ZRANGE');
                foreach ($redis as $key => $value) {
                    D($key . ' - ' . $value);
                }
                D($redis->assoc);
            });

            $this->redis->zrange('myzset', 0, -1, 'WITHSCORES', function ($redis) {
                D('TEST 4: ZRANGE WITHSCORES');
                foreach ($redis as $key => $value) {
                    D($key . ' - ' . $value);
                }
                D($redis->assoc);
            });
        });

        $this->redis->subscribe('mysub', function ($redis) {
            D('TEST 5: SUB & PUB');
            foreach ($redis as $key => $value) {
                D($key . ' - ' . $value);
            }
            D($redis->channel, $redis->msg, $redis->assoc);
        });

        $this->redis->publish('mysub', 'Test message!');
    }