Called when the connection is handshaked (at low-level), and peer is ready to recv. data
@return void
558167
public function onReady()
    {
        if (static::$requestCommandListFlipped === null) {
            static::$requestCommandListFlipped = array_flip(static::$requestCommandList);
        }
        if (static::$responseCommandListFlipped === null) {
            static::$responseCommandListFlipped = array_flip(static::$responseCommandList);
        }
        parent::onReady();
    }
804858
public function onConnected($cb)
    {
        if ($this->state === self::CONN_STATE_HANDSHAKED_ERROR) {
            $cb($this);
        } elseif ($this->state === self::CONN_STATE_HANDSHAKED_OK) {
            $cb($this);
        } else {
            if (!$this->onConnected) {
                $this->onConnected = new StackCallbacks();
            }

            $this->onConnected->push($cb);
        }
    }
848783
protected function handshake()
    {
        if (null !== $this->session) {
            return;
        }

        $query = ['use_b64'   => $this->options['use_b64'],
                  'EIO'       => $this->options['version'],
                  'transport' => $this->options['transport']];

        if (isset($this->url['query'])) {
            $query = \array_replace($query, $this->url['query']);
        }

        $context = $this->context;
        $protocol = true === $this->url['secured'] ? 'ssl' : 'http';

        if (!isset($context[$protocol])) {
            $context[$protocol] = [];
        }

        // add customer headers
        if (isset($this->options['headers'])) {
            $headers = isset($context[$protocol]['header']) ? $context[$protocol]['header'] : [];
            $context[$protocol]['header'] = \array_merge($headers, $this->options['headers']);
        }

        $url    = \sprintf(
            '%s://%s:%d/%s/?%s',
            $this->url['scheme'],
            $this->url['host'],
            $this->url['port'],
            \trim($this->url['path'], '/'),
            \http_build_query($query)
        );

        $result = @\file_get_contents($url, false, \stream_context_create($context));

        if (false === $result) {
            $message = null;
            $error = \error_get_last();

            if (null !== $error && false !== \strpos($error['message'], 'file_get_contents()')) {
                $message = $error['message'];
            }

            throw new ServerConnectionFailureException($message);
        }

        $open_curly_at = \strpos($result, '{');
        $todecode = \substr($result, $open_curly_at, \strrpos($result, '}')-$open_curly_at+1);
        $decoded = \json_decode($todecode, true);

        if (!\in_array('websocket', $decoded['upgrades'])) {
            throw new UnsupportedTransportException('websocket');
        }

        $cookies = [];
        foreach ($http_response_header as $header) {
            if (\preg_match('/^Set-Cookie:\s*([^;]*)/i', $header, $matches)) {
                $cookies[] = $matches[1];
            }
        }
        $this->cookies = $cookies;

        $this->session = new Session(
            $decoded['sid'],
            $decoded['pingInterval'] / 1000,
            $decoded['pingTimeout'] / 1000,
            $decoded['upgrades']
        );
    }
1373806
private function connect()
    {
        $this->_state = parent::STATE_STARTING;

        // Build the URL and parse it
        $protocol = 'http' . ($this->_user->useSSL() ? 's' : '');
        if ($this->_is_multi) {
            $url = $protocol . '://' . $this->_user->getStreamUrl() . 'multi';
        } else {
            $url = $protocol . '://' . $this->_user->getStreamUrl() . $this->_definition->getHash();
        }
        $url = parse_url($url);

        // Fill in some defaults if any required bits are missing
        if (empty($url['port'])) {
            $url['port'] = 80;
        }

        // Build the request headers
        $request = array();
        $params = array(
            'statuses' => 'true',
        );
        if ($this->_is_multi) {
            $params['hashes'] = implode(',', $this->_hashes);
        }
        $request[] = 'GET ' . $url['path'] . '?' . http_build_query($params) . ' HTTP/1.1';
        $request[] = 'Host: ' . $url['host'];
        $request[] = 'User-Agent: ' . $this->_user->getUserAgent();
        $request[] = 'Auth: ' . $this->_user->getUsername() . ':' . $this->_user->getAPIKey();
        $request[] = 'Accept: */*';

        $connection_delay = 0;

        do {
            // Back off a bit if required
            if ($connection_delay > 0) {
                sleep($connection_delay);
            }

            // Make the connection
            $this->_conn = fsockopen('tcp://' . $url['host'], $url['port'], $err, $errno, $this->_connect_timeout);

            // Catch failures
            if (! $this->_conn or ! is_resource($this->_conn)) {
                // Connection failed
                $this->_conn = false;
            } else {
                // Blocking while we do the secret handshake
                stream_set_blocking($this->_conn, 1);

                // Send the request
                foreach ($request as $line) {
                    fwrite($this->_conn, $line . "\r\n");
                }

                // A blank line indicates the end of the request
                fwrite($this->_conn, "\r\n");

                // Read the response headers
                $response = array();
                $line = true;
                while ($line) {
                    $line = trim(fgets($this->_conn, $this->_max_line_length));
                    $response[] = $line;
                }
            }

            // If the connection failed or
            if ($this->_conn and count($response) == 1 and strlen(trim($response[0])) == 0) {
                // Connection failed or timed out
                // Timings from http://dev.datasift.com/docs/streaming-api
                if ($connection_delay == 0) {
                    $connection_delay = 1;
                } elseif ($connection_delay < 16) {
                    $connection_delay++;
                } else {
                    throw new DataSift_Exception_StreamError('Connection failed due to a network error');
                }
            } else {
                // Check the first line to make sure it's a positive response
                list($http, $code, $message) = preg_split('|\s+|', $response[0], 3);

                if ($code == '200') {
                    // Success!
                    $this->_state = parent::STATE_RUNNING;
                } elseif ($code >= '400' && $code < 500 && $code != 420) {
                    // Connection refused, find out why
                    $line = '';
                    while (strlen($line) < 10) {
                        $line = trim(fgets($this->_conn, $this->_max_line_length));
                    }
                    $data = json_decode($line, true);
                    if (isset($data['message'])) {
                        throw new DataSift_Exception_StreamError($data['message']);
                    } else {
                        throw new DataSift_Exception_StreamError('Connection refused: ' . $code . ' ' . $message);
                    }
                } else {
                    // Connection failed, back off a bit and try again
                    // Timings from http://dev.datasift.com/docs/streaming-api
                    if ($connection_delay == 0) {
                        $connection_delay = 10;
                    } elseif ($connection_delay < 320) {
                        $connection_delay *= 2;
                    } else {
                        throw new DataSift_Exception_StreamError('Connection failed: ' . $code . ' ' . $message);
                    }
                }
            }
        } while ($this->_state != parent::STATE_RUNNING);

        // Set the stream as non-blocking
        stream_set_blocking($this->_conn, 0);
    }
829828
private void setHandshakeSuccess() {
        handshakePromise.trySuccess(ctx.channel());

        if (logger.isDebugEnabled()) {
            logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite());
        }
        ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);

        if (readDuringHandshake && !ctx.channel().config().isAutoRead()) {
            readDuringHandshake = false;
            ctx.read();
        }
    }
1224585
public function listen(): void
    {
        $this->socket->listen();
        $this->resources[$this->socket->getResourceId()] = $this->socket->getResource();
    }
950988
public function onReady()
    {
        $conn = $this;
        $this->keepaliveTimer = setTimeout(function ($timer) use ($conn) {
            $conn->ping();
        }, 10e6);
    }
1351131
public function connect(): bool
    {
        if ($this->isConnected()) {
            return false;
        }

        try {
            $this->socket->connect();
        } catch (\Exception $ex) {
            return false;
        }

        $key = $this->protocol->generateKey();
        $handshake = $this->protocol->getRequestHandshake(
            $this->uri,
            $key,
            $this->origin,
            $this->headers
        );

        $this->socket->send($handshake);
        $response = $this->socket->receive(self::MAX_HANDSHAKE_RESPONSE);
        return ($this->connected =
            $this->protocol->validateResponseHandshake($response, $key));
    }
1299904
public function onRead()
    {
        if ($this->state === self::STATE_DATAFLOW) {
            // Data exchange
            if ($this->slave) {
                do {
                    $this->slave->writeFromBuffer($this->bev->input, $this->bev->input->length);
                } while ($this->bev->input->length > 0);
            }

            return;
        }

        start:

        $l = $this->bev->input->length;

        if ($this->state === self::STATE_ROOT) {
            // Start
            if ($l < 2) {
                // Not enough data yet
                return;
            }
            $n = ord($this->look(1, 1));
            if ($l < $n + 2) {
                // Not enough data yet
                return;
            }
            $this->ver = $this->look(1);
            $this->drain(2);
            $methods = $this->read($n);

            if (!$this->pool->config->auth->value) {
                // No auth
                $m = "\x00";
                $this->state = self::STATE_AUTHORIZED;
            } elseif (mb_orig_strpos($methods, "\x02") !== false) {
                // Username/Password authentication
                $m = "\x02";
                $this->state = self::STATE_HANDSHAKED;
            } else {
                // No allowed methods
                $m = "\xFF";
                $this->state = self::STATE_ABORTED;
            }

            $this->write($this->ver . $m);

            if ($this->state === self::STATE_ABORTED) {
                $this->finish();
            } else {
                goto start;
            }
        } elseif ($this->state === self::STATE_HANDSHAKED) {
            // Handshaked
            if ($l < 3) {
                // Not enough data yet
                return;
            }

            $ver = $this->look(1);

            if ($ver !== $this->ver) {
                $this->finish();
                return;
            }

            $ulen = ord($this->look(1, 1));
            if ($l < 3 + $ulen) {
                // Not enough data yet
                return;
            }
            $username = $this->look(2, $ulen);
            $plen = ord($this->look(2 + $ulen, 1));

            if ($l < 3 + $ulen + $plen) {
                // Not enough data yet
                return;
            }
            $this->drain(3 + $ulen);
            $password = $this->read($plen);

            if (($username !== $this->pool->config->username->value)
                || ($password !== $this->pool->config->password->value)
            ) {
                $this->state = self::STATE_ABORTED;
                $m = "\x01";
            } else {
                $this->state = self::STATE_AUTHORIZED;
                $m = "\x00";
            }
            $this->write($this->ver . $m);

            if ($this->state === self::STATE_ABORTED) {
                $this->finish();
            } else {
                goto start;
            }
        } elseif ($this->state === self::STATE_AUTHORIZED) {
            // Ready for query
            if ($l < 4) {
                // Not enough data yet
                return;
            }
            $ver = $this->read(1);

            if ($ver !== $this->ver) {
                $this->finish();
                return;
            }

            $cmd = $this->read(1);
            $this->drain(1);
            $atype = $this->read(1);
            if ($atype === "\x01") {
                $address = inet_ntop($this->read(4));
            } elseif ($atype === "\x03") {
                $len = ord($this->read(1));
                $address = $this->read($len);
            } elseif ($atype === "\x04") {
                $address = inet_ntop($this->read(16));
            } else {
                $this->finish();
                return;
            }

            $u = unpack('nport', $this->read(2));
            $port = $u['port'];

            $this->destAddr = $address;
            $this->destPort = $port;
            $this->pool->connect('tcp://' . $this->destAddr . ':' . $this->destPort, function ($conn) {
                if (!$conn) {
                    // Early connection error
                    $this->write($this->ver . "\x05");
                    $this->finish();
                } else {
                    $conn->setClient($this);
                    $this->state = self::STATE_DATAFLOW;
                    $conn->getSocketName($addr, $port);
                    $this->slave = $conn;
                    $this->onSlaveReady(0x00, $addr, $port);
                    $this->onReadEv(null);
                }
            }, 'SocksServerSlaveConnection');
        }
    }
354111
function recv()
    {
        if (!$this->handshake)
        {
            trigger_error("not complete handshake.");
            return false;
        }
        if ($this->buffer and  $offset = stripos($this->buffer,"\r\n\r\n") !== false)
        {
            $packet = substr($this->buffer, 0, $offset + 4);
            $next = substr($this->buffer, $offset + 4);
            if ($next) {
                $this->buffer = $next;
            }
            $this->parser->push($packet);
            $frame = $this->parser->pop();
            if ($frame)
            {
                return $frame->data;
            }
        } else {
            while (true)
            {
                $data = $this->socket->recv();
                if ($this->buffer) {
                    $data = $this->buffer.$data;
                    $this->buffer = '';
                }
                if (!$data)
                {
                    return false;
                }
                $this->parser->push($data);
                $frame = $this->parser->pop();
                if ($frame)
                {
                    return $frame->data;
                }
            }
        }
        return false;
    }
343338
public function resumeAccept()
    {
        // Register a listener to be notified when server socket is ready to read.
        if (static::$globalEvent && true === $this->_pauseAccept && $this->_mainSocket) {
            if ($this->transport !== 'udp') {
                static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
            } else {
                static::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptUdpConnection'));
            }
            $this->_pauseAccept = false;
        }
    }
124091
protected function doStep()
    {
        // Wait for the next read request
        /** @var ReadRequest $req */
        $req = $this->decoder->decode(ReadRequest::class);
        try {
            $this->checkUnsupportedTypes($req->getIds());
            $entities = $this->read($req->getIds());
            $res = ReadResponse::success($entities);
        } catch (Exception $ex) {
            $res = ReadResponse::error($ex);
        }
        // Send the result back to the host
        $this->encoder->encode($res);
    }
1235179
public function syn()
  {
    if(!isset($this->options["port"]) || empty($this->options["port"])) $this->options["port"] = $this->default_port;

    $this->initTransport($this->options);
    $this->transport->setAdapter($this);

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

    TeamSpeak3_Helper_Signal::getInstance()->emit("tsdnsConnected", $this);
  }
738202
public function onReady()
    {
        if ($this->isEnabled()) {
            $this->updateTimer = setTimeout(function ($timer) {
                $this->updateAllServers();
                $timer->timeout(2e6);
            }, 1);
        }
    }
1197711
public function syn()
  {
    $this->initTransport($this->options);
    $this->transport->setAdapter($this);

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

    TeamSpeak3_Helper_Signal::getInstance()->emit("filetransferConnected", $this);
  }
1149789
public function onReady()
    {
        parent::onReady();
        $this->WS = \PHPDaemon\Servers\WebSocket\Pool::getInstance($this->config->wssname->value, false);
    }
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);
  }