legionth/http-client-react

v1.1.0 2018-09-15 23:42 UTC

This package is not auto-updated.

Last update: 2024-09-17 08:38:09 UTC


README

使用 PHP 在 ReactPHP 之上编写的 HTTP 客户端。

目录

使用方法

客户端负责向服务器发送 HTTP 请求并接收 HTTP 响应。

此库使用 PSR-7 对象来简化 HTTP-Messsages 的处理。

$uri = 'tcp://httpbin.org:80';
$request = new Request('GET', 'http://httpbin.org');

$promise = $client->request($uri, $request);

从服务器到客户端传输响应可能需要一些时间。因此,`request` 方法将返回一个 ReactPHP promise

这个承诺将产生一个 PSR-7 响应对象

$promise = $client->request($uri, $request);
$promise->then(
    function (\Psr\Http\Message\ResponseInterface $response) {
        echo 'Successfully received a response from the server:' . PHP_EOL;
        echo RingCentral\Psr7\str($response);
    },
    function (\Exception $exception) {
        echo $exception->getMessage() . PHP_EOL;
    }
);

响应体将始终是异步的 ReactPHP Stream

$promise = $client->request($uri, $request);
$promise->then(
    function (ResponseInterface $response) {
        echo 'Successfully received a response from the server:' . PHP_EOL;
        echo RingCentral\Psr7\str($response);

        $body = $response->getBody();
        $body->on('data', function ($data) {
            echo "Body-Data: " . $data . PHP_EOL;
        });

        $body->on('end', function () {
            exit(0);
        });
    },
    function (\Exception $exception) {
        echo $exception->getMessage() . PHP_EOL;
    }
);

当 HTTP 响应的完整主体传输到客户端时,将触发 end 事件。在上面的示例中,它将退出当前脚本。

请求体

您还可以将 ReactPHP Stream 添加到请求体中,以便通过它流式传输数据。如果使用此方法,主体将始终以分块编码方式传输,任何如 Content-Length 或其他 Transfer-Encoding 标头将被替换。

$stream = new ReadableStream();

$timer = $loop->addPeriodicTimer(0.5, function () use ($stream) {
    $stream->emit('data', array(microtime(true) . PHP_EOL));
});

$loop->addTimer(5, function() use ($loop, $timer, $stream) {
    $loop->cancelTimer($timer);
    $stream->emit('end');
});

$request = new Request(
    'POST',
    'http://127.0.0.1:10000',
    array(
        'Host' => '127.0.0.1',
        'Content-Type' => 'text/plain'
    ),
    $stream
);
$promise = $client->request($uri, $request);

此示例将每 0.5 秒向服务器传输一个分块编码的数据块。主体传输将在 5 秒后结束。

查看 examples 文件夹以自行尝试。

安装

新用户 Composer?

这将安装最新支持的版本

$ composer require legionth/http-client-react:^0.1

许可证

MIT