swoole--协程 Http2 客户端

2021-05-23
use Swoole\Http2\Request;
use Swoole\Coroutine\Http2\Client;
use function Swoole\Coroutine\run;
use Swoole\Http2\Request;

run(function () {
    $cli = new Client(string $host, int $port, bool $open_ssl = false);

    // 设置客户端参数,
    $cli->set([
        'timeout' => -1,
        'ssl_host_name' => $domain
    ]);
    // 连接到目标服务器。
    $cli->connect();
    
    $request = new Request();
    // 设置请求头数组
    $request->headers = [];
    // 设置请求方法
    $request->method = '';
    // 设置请求路径,必须以/作为开始
    $request->path = '';
    // 设置cookie数组
    $request->cookies = [];
    // 设置请求体,字符串数据作为RAW form-data进行发送,数组数据以Content-Type为application/x-www-form-urlencoded发送
    $request->data = [];
    // 设置true时发送数据后不关闭stream流,可以多次调用write方法,向服务器发送数据帧,默认false发送数据后直接关闭stream流
    $request->pipeline = true;
    // 向服务器发送请求,底层会自动建立一个Http2的stream。可以同时发起多个请求,返回流编号
    $cli->send($request);

    // 向服务器发送更多数据帧,可以多次调用write向同一个stream写入数据帧
    // 对流编号$streamId发送数据$data,$end为true是关闭流,无法继续写入数据
    $cli->write($streamId, $data, $end = false);

     // PING帧是一种机制,用于测量来自发送方的最小往返时间,以及确定空闲连接是否仍然有效。
     $cli->ping();

     // 接收请求,成功后返回Swoole\Http2\Response对象
     $cli->recv($timeout);
 
     // 接收请求,成功后返回Swoole\Http2\Response对象,对于pipeline类型的响应read可以分多次读取
     $cli->read(float $timeout);
     
     // 关闭连接
     $cli->close();
});

 

{/if}