# 异步Http/WebSocket客户端

建议先阅读官方文档[异步Http/WebSocket客户端](https://wiki.swoole.com/wiki/page/p-http_client.html)章节

**一、为什么需要异步**&#x20;

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

**二、异步Http/WebSocket客户端**&#x20;

1、默认发送get及post请求

```
$host如果为域名底层需要进行一次DNS查询才能得到ip地址，这是阻塞IO，所以使用`Swoole\Async::dnsLookup`实现异步非阻塞
```

```php
<?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、自定义请求类型

```php
$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
<?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');
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/swoole/swoole-ji-chu/yi-bu-fei-du-sai-io/yi-bu-http-websocket-ke-hu-duan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
