× 警告!旧版文档已经暂停维护,请查看新版文档。点击前往新版文档

Http2

4.2.0以后移除了异步Http2客户端, 请使用协程Http2客户端

Swoole-1.9.7增加了对Http2.0客户端的支持。新增的客户端类名为Swoole\Http2\Client,继承自Swoole\Client,实现了Http2.0客户端协议的完整支持。

Http2.0客户端与Http1.1的最大差别是2.0支持了Stream并发机制,可以同时发起多个GETPOST请求。最大并发数量受限与服务器端规定的max_concurrent_streams设置。

编译安装

需要依赖nghttp2库,编译Swoole扩展时需要设置--enable-http2--enable-openssl--with-openssl-dir

使用示例

$array = array(
    "host" => "www.jd.com",
    "accept-encoding" => "gzip, deflate",
    'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'accept-language' => 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2',
    'user-agent' => 'Mozilla/5.0 (X11; Linux x86_64) Chrome/58.0.3026.3 Safari/537.36',
);

$client = new Swoole\Http2\Client("www.jd.com", 443, true);

$client->setHeaders($array);
$client->setCookies(array("a" => "1", "b" => "2"));

$client->get("/", function ($o) use($client) {
    echo "#{$client->sock} hello world 1\n";
    echo $o->body;
});

$client->post("/", $array, function ($o) use($client) {
    echo "{$client->sock} hello world 3\n";
    echo $o->body;
    $client->close();
});
Swoole\Event::wait();

  • 猫空

    报错 Uncaught Error: Class 'Swoole\Http2\Client' not found in 这个也一样new swoole_http_client($host,$port,true); 都没法用 版本2.0.12的

  • 谁伴我闯荡

    同楼上,Fatal error: Uncaught Error: Class 'Swoole\Http2\Client' not found in,版本2.0.9

  • 谁伴我闯荡

    要注意:需要依赖nghttp2库,编译Swoole扩展时需要设置--enable-http2、--enable-openssl或--with-openssl-dir。

  • 秃子

    .configure --enable-http2

  • 秃子

    不执行回调函数

  • 平平仄仄的韵律

    最大并发数量受限与服务器端规定的max_concurrent_streams设置,这个设置在哪能看到和设置?

  • 平平仄仄的韵律

    同时发起多个GET或POST请求,并发多了是不是内存就爆了?

  • 13641164576

    --ri swool 如下 http2 开启了 但是还是 提示 Fatal error: Uncaught Error: Class 'Swoole\Http2\Client' not found in,

    Swoole => enabled Author => Swoole Team Version => 4.3.5 Built => Jul 14 2019 19:41:40 coroutine => enabled epoll => enabled eventfd => enabled signalfd => enabled cpu_affinity => enabled spinlock => enabled rwlock => enabled sockets => enabled openssl => OpenSSL 1.0.2r 26 Feb 2019 http2 => enabled pcre => enabled zlib => enabled mutex_timedlock => enabled pthread_barrier => enabled futex => enabled async_redis => enabled