@param string                          $uri
@param Socket\ServerListenContext|null $listenContext
@param Socket\ServerTlsContext|null    $tlsContext

@return Promise
541506
public static function listen(
        string $uri,
        Socket\ServerListenContext $listenContext = null,
        Socket\ServerTlsContext $tlsContext = null
    ): Promise {
        return call(function () use ($uri, $listenContext, $tlsContext) {
            if (!self::isWorker()) {
                return Socket\listen($uri, $listenContext, $tlsContext);
            }

            $listenContext = $listenContext ?? new Socket\ServerListenContext;

            if (canReusePort()) {
                $position = \strrpos($uri, ":");
                $port = $position ? (int) \substr($uri, $position) : 0;

                if ($port === 0) {
                    $uri = yield self::$client->selectPort($uri);
                }

                $listenContext = $listenContext->withReusePort();
                return Socket\listen($uri, $listenContext, $tlsContext);
            }

            $socket = yield self::$client->importSocket($uri);
            return self::listenOnBoundSocket($socket, $listenContext, $tlsContext);
        });
    }
276530
public function join(string $listenAddress,
                         string $advertiseAddress,
                         string $dataPathAddress,
                         string $remoteAddress,
                         string $joinToken)
    {
        $data = [
            'ListenAddr' => $listenAddress,
            'AdvertiseAddr' => $advertiseAddress,
            'DataPathAddr' => $dataPathAddress,
            'RemoteAddrs' => $remoteAddress,
            'JoinToken' => $joinToken,
        ];

        $url = $this->url.'/join';

        $request = json_encode($data);

        return $this->curl->post($url, $request, self::$header);
    }
1129226
public function connectAsync(ConnectionContext $ctx, string $header = ''): \Generator
    {
        $ctx = $ctx->getCtx();
        $uri = $ctx->getUri();
        $ctx->setUri('tcp://'.$this->extra['address'].':'.$this->extra['port'])->secure(false);

        $this->stream = yield $ctx->getStream();

        $address = $uri->getHost();
        $port = $uri->getPort();

        yield $this->stream->write("CONNECT $address:$port HTTP/1.1\r\nHost: $address:$port\r\nAccept: */*\r\n".$this->getProxyAuthHeader()."Connection: keep-Alive\r\n\r\n");

        $buffer = yield $this->stream->getReadBuffer($l);
        $headers = '';
        $was_crlf = false;
        while (true) {
            $piece = yield $buffer->bufferRead(2);
            $headers .= $piece;
            if ($piece === "\n\r") { // Assume end of headers with \r\n\r\n
                $headers .= yield $buffer->bufferRead(1);
                break;
            }
            if ($was_crlf && $piece === "\r\n") {
                break;
            }
            $was_crlf = $piece === "\r\n";
        }
        $headers = explode("\r\n", $headers);

        list($protocol, $code, $description) = explode(' ', $headers[0], 3);
        list($protocol, $protocol_version) = explode('/', $protocol);
        if ($protocol !== 'HTTP') {
            throw new \danog\MadelineProto\Exception('Wrong protocol');
        }
        $code = (int) $code;
        unset($headers[0]);
        if (array_pop($headers).array_pop($headers) !== '') {
            throw new \danog\MadelineProto\Exception('Wrong last header');
        }
        foreach ($headers as $key => $current_header) {
            unset($headers[$key]);
            $current_header = explode(':', $current_header, 2);
            $headers[strtolower($current_header[0])] = trim($current_header[1]);
        }

        $close = $protocol === 'HTTP/1.0';
        if (isset($headers['connection'])) {
            $close = strtolower($headers['connection']) === 'close';
        }

        if ($code !== 200) {
            $read = '';
            if (isset($headers['content-length'])) {
                $read = yield $buffer->bufferRead((int) $headers['content-length']);
            }

            if ($close) {
                $this->disconnect();
                yield $this->connect($this->ctx);
            }

            \danog\MadelineProto\Logger::log(trim($read));

            throw new \danog\MadelineProto\Exception($description, $code);
        }

        if ($close) {
            yield $this->stream->disconnect();
            yield $this->stream->connect($ctx);
        }
        if (isset($headers['content-length'])) {
            $length = (int) $headers['content-length'];
            $read = yield $buffer->bufferRead($length);
        }
        \danog\MadelineProto\Logger::log('Connected to '.$address.':'.$port.' via http');

        if (strlen($header)) {
            yield (yield $this->stream->getWriteBuffer(strlen($header)))->bufferWrite($header);
        }
    }
483579
public final function withUri(
       UriInterface $uri,
       $preserveHost = false): RequestInterface
   {
       if (true === $preserveHost
        && !array_key_exists("Host", $this->header)
        && $uri->getHost()) {
           return $this->with("uri", $uri)->withHeader("Host", $uri->getHost());
       }
       return $this->with("uri", $uri);
   }
788105
protected function initCurlHandler($uri)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_USERAGENT, 'twelvelabs/foursquare client');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->verifyHost);

        if ($this->verifyPeer === false) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        } else {

            // @see http://curl.haxx.se/docs/caextract.html

            if (!file_exists($this->certificatePath)) {
                throw new \RuntimeException('cacert.pem file not found');
            }

            curl_setopt ($ch, CURLOPT_CAINFO, $this->certificatePath);

        }

        return $ch;

    }
1167209
public function setProxy($proxyUri, $requestFullUri = false)
    {
        $this->proxyUri = $proxyUri;
        $this->requestFullUri = $requestFullUri;

        $this->socketClient->setContext($this->getContext());
    }
1141023
async function connectToServer(client, config) {
  return new Promise((resolve, reject) => {
    client
      .on('ready', error => (error ? reject(error) : resolve(client)))
      .on('error', error => reject(error))
      .connect(config);
  });
}
849478
public function listen(Queue ...$queues): Promise
    {
        /** Hack for phpunit tests */
        $isTestCall = 'phpunitTests' === (string) \getenv('SERVICE_BUS_TESTING');

        /**
         * @psalm-suppress InvalidArgument Incorrect psalm unpack parameters (...$args)
         * @psalm-suppress MixedArgument
         */
        return call(
            function(array $queues) use ($isTestCall): \Generator
            {
                /** @psalm-suppress TooManyTemplateParams */
                yield $this->transport->consume(
                    function(IncomingPackage $package) use ($isTestCall): \Generator
                    {
                        $this->currentTasksInProgressCount++;

                        /** Hack for phpUnit */
                        if (true === $isTestCall)
                        {
                            $this->currentTasksInProgressCount--;

                            yield $this->processor->handle($package);
                            yield $this->transport->stop();

                            Loop::stop();
                        }

                        /** Handle incoming package */
                        $this->deferExecution($package);

                        /** Limit the maximum number of concurrently running tasks */
                        while ($this->maxConcurrentTaskCount <= $this->currentTasksInProgressCount)
                        {
                            yield new Delayed($this->awaitDelay);
                        }
                    },
                    ...$queues
                );
            },
            $queues
        );
    }
636588
public function connect(ConnectionContext $ctx, string $header = ''): Promise
    {
        $this->in_seq_no = -1;
        $this->out_seq_no = -1;
        $this->stream = new HashedBufferedStream();
        $this->stream->setExtra('crc32b_rev');

        return $this->stream->connect($ctx, $header);
    }
371383
@Override
  public void connect(
      ChannelHandlerContext ctx,
      SocketAddress remoteAddress,
      SocketAddress localAddress,
      ChannelPromise promise) throws Exception {
    final class ConnectListener implements ChannelFutureListener {
      @Override
      public void operationComplete(ChannelFuture future) {
        if (!future.isSuccess()) {
          failWrites(future.cause());
        }
      }
    }

    super.connect(ctx, remoteAddress, localAddress, promise);
    promise.addListener(new ConnectListener());
  }
988249
public function submit(FormResponseContract $listener, Request $request)
    {
        $response = (array) $this->dispatcher->fire(new SecurityFormSubmitted($listener, $request));
        if (count($response)) {
            return $response[0];
        }

        return null;
    }
1114947
function WSMux(urlOrWs, options) {
  EventEmitter.call(this);
  this.options = util._extend({mask: true}, options);
  this.closed = false;
  this.channels = {};
  this.pending = [];
  this._openWebsocket(urlOrWs);
}
945646
public function dispatch($uri, $state, Event &$event = null) {

        $this->logger->addDebug("dispatch called for $uri with state set to $state");

        if (!array_key_exists($uri, $this->listeners)) {
            $this->logger->addDebug("no listeners found for $uri with state set to $state");

            return;
        }

        $this->logger->addDebug("listeners found - iterating");

        foreach ($this->listeners[$uri] as $listener) {
            $listener->setState($state, $event);
        }
    }
951454
public function callback(ServerRequestInterface $request)
    {
        $response = new Response(200, [
            'Content-Type' => 'text/plain; charset=utf-8',
        ], '');

        return new Promise(function ($resolve, $reject) use (&$request, &$response) {
            try {
                $context = new Context($request, $response);
                $context->setLogger($this->getLogger());

                /**
                 * @var HttpBodyStream $body
                 */
                $body = $request->getBody();
                $body->on('data', function ($data) use (&$request, &$context) {
                    if (!$data) return;
                    $method = $request->getMethod();
                    $contentType = $request->getHeader('Content-Type');
                    if (isset($contentType[0])
                        && (strcasecmp($method, 'POST') === 0 || strcasecmp($method, 'PUT') === 0)
                    ) {
                        if (strpos(strtolower($contentType[0]), 'application/x-www-form-urlencoded') !== false) {
                            parse_str($data, $parsedBody);
                            $request = $request->withParsedBody($parsedBody);
                            $context->setRequest($request);
                        } else if (strpos(strtolower($contentType[0]), 'application/json') !== false) {
                            $parsedBody = json_decode($data, JSON_OBJECT_AS_ARRAY);
                            $request = $request->withParsedBody($parsedBody);
                            $context->setRequest($request);
                        }
                    }
                    $context->setAttribut('httpRawData', $data);
                });
                $body->on('end', function () use (&$context, $resolve) {
                    co(...$this->middlewares)($context);
                    $resolve($context->getReturn());
                });
                $body->on('error', function ($reason) use ($reject) {
                    $reject($reason);
                });
            } catch (\Throwable $exception) {
                // 触发错误异常处理中间件
                $this->onException($exception, $context);
                $rsp = $context->getResponse();
                if ($rsp === $response) {
                    $rsp = $response->withStatus(500);
                    $response->getBody()->write('Internal Server Error');
                }
                $resolve($rsp);
            }
        });
    }
1128407
public static function loadFromProvisioningUri(string $uri): OTPInterface
    {
        $parsed_url = parse_url($uri);
        Assertion::isArray($parsed_url, 'Not a valid OTP provisioning URI');
        self::checkData($parsed_url);

        $otp = self::createOTP($parsed_url);

        self::populateOTP($otp, $parsed_url);

        return $otp;
    }
1356027
public function activateCertificate($serverId, $siteId, $certificateId, $wait = true)
    {
        $this->post("servers/$serverId/sites/$siteId/certificates/$certificateId/activate");

        if ($wait) {
            $this->retry(30, function () use ($serverId, $siteId, $certificateId) {
                $certificate = $this->certificate($serverId, $siteId, $certificateId);

                return $certificate->activationStatus == 'activated';
            });
        }
    }
1122191
public void addSslListener(InetSocketAddress addr, Configuration sslConf,
      boolean needClientAuth) throws IOException {
    if (webServer.isStarted()) {
      throw new IOException("Failed to add ssl listener");
    }
    if (needClientAuth) {
      // setting up SSL truststore for authenticating clients
      System.setProperty("javax.net.ssl.trustStore", sslConf.get(
          "ssl.server.truststore.location", ""));
      System.setProperty("javax.net.ssl.trustStorePassword", sslConf.get(
          "ssl.server.truststore.password", ""));
      System.setProperty("javax.net.ssl.trustStoreType", sslConf.get(
          "ssl.server.truststore.type", "jks"));
    }
    SslSocketConnector sslListener = new SslSocketConnector();
    sslListener.setHost(addr.getAddress().getHostAddress());
    sslListener.setPort(addr.getPort());
    sslListener.setKeystore(sslConf.get("ssl.server.keystore.location"));
    sslListener.setPassword(sslConf.get("ssl.server.keystore.password", ""));
    sslListener.setKeyPassword(sslConf.get("ssl.server.keystore.keypassword", ""));
    sslListener.setKeystoreType(sslConf.get("ssl.server.keystore.type", "jks"));
    sslListener.setNeedClientAuth(needClientAuth);
    webServer.addConnector(sslListener);
  }