react/http-client

(要求Workerman版本>=3.3.6)

安装:

  1. composer require react/http-client

示例:

  1. <?php
  2. require_once __DIR__ . '/vendor/autoload.php';
  3. use Workerman\Worker;
  4. $worker = new Worker('text://0.0.0.0:6161');
  5. $worker->onWorkerStart = function() {
  6. global $client;
  7. $loop = Worker::getEventLoop();
  8. $factory = new React\Dns\Resolver\Factory();
  9. $dns = $factory->createCached('8.8.8.8', $loop);
  10. $factory = new React\HttpClient\Factory();
  11. $client = $factory->create($loop, $dns);
  12. };
  13. $worker->onMessage = function($connection, $host) {
  14. global $client;
  15. $request = $client->request('GET', $host);
  16. $request->on('error', function(Exception $e) use ($connection) {
  17. $connection->send($e);
  18. });
  19. $request->on('response', function ($response) use ($connection) {
  20. $response->on('data', function ($data, $response) use ($connection) {
  21. $connection->send($data);
  22. });
  23. });
  24. $request->end();
  25. };
  26. Worker::runAll();

文档:

https://github.com/reactphp/http-client

注意:

1、所有的异步编码必须在onXXX回调中编写

2、异步客户端需要的$loop变量请使用Worker::getEventLoop();返回值