异步Http/WebSocket客户端

建议先阅读官方文档异步Http/WebSocket客户端章节

一、为什么需要异步

通常我们进行 http 请求都是通过 curl 或者 file_get_contents,但是并发的性能都不好,都是同步执行,需要等待请求执行完成才能执行下一步操作,Swoole 内置的 swoole_http_client(Http 异步客户端)没有并发限制,当你的程序读取网络或磁盘时。swoole会加入到事件监听中,完全不需要等待,你的代码可以取做别的事情。当网络或磁盘读取完成,返回数据时,再继续向下执行你的代码。

二、异步Http/WebSocket客户端

1、默认发送get及post请求

$host如果为域名底层需要进行一次DNS查询才能得到ip地址,这是阻塞IO,所以使用`Swoole\Async::dnsLookup`实现异步非阻塞
<?php
//dns解析
Swoole\Async::dnsLookup("www.baidu.com", function ($domainName, $ip) {

    $client = new swoole_http_client($ip, 80);
   //设置请求头
    $client->setHeaders([
        'Accept' => 'text/html,application/xhtml+xml,application/xml',
        'Accept-Encoding' => 'gzip',
    ]);

    //发送get请求
    $client->get('/', function ($cli) {
        echo "Length: " . strlen($cli->body) . "\n";
        echo $cli->body;
    });
});

echo '是不是同步执行';

2、自定义请求类型

$client = new swoole_http_client('218.64.129.244', 9500);
//设置请求头
$client->setHeaders([
    'Accept' => 'text/html,application/xhtml+xml,application/xml',
    'Accept-Encoding' => 'gzip',
]);

//自定义请求类型 PUT
$client->setMethod('PUT');
$client->setData(['name'=>'peter']);
$client->execute('/',function ($cli){
    var_dump($cli);

});

3.http请求改造升级为websocket

通过upgrade方法发起WebSocket握手请求,并将连接升级为WebSocket

<?php

$client = new swoole_http_client('218.64.129.244', 9500);

//监听服务端给我们发送的数据
$client->on('message',function ($cli,$frame){
    var_dump($frame);
});

//websocket建立的是一个长连接
$client->upgrade('/',function ($cli){
    $cli->push('hello world');
});

Last updated