11-http-client.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. // Simple plaintext HTTP client example (for illustration purposes only).
  3. // This shows how a plaintext TCP/IP connection is established to then send an
  4. // application level protocol message (HTTP).
  5. // Real applications should use react/http-client instead!
  6. //
  7. // This simple example only accepts an optional host parameter to send the
  8. // request to. See also example #22 for proper URI parsing.
  9. //
  10. // $ php examples/11-http-client.php
  11. // $ php examples/11-http-client.php reactphp.org
  12. use React\Socket\Connector;
  13. use React\Socket\ConnectionInterface;
  14. $host = isset($argv[1]) ? $argv[1] : 'www.google.com';
  15. require __DIR__ . '/../vendor/autoload.php';
  16. $connector = new Connector();
  17. $connector->connect($host. ':80')->then(function (ConnectionInterface $connection) use ($host) {
  18. $connection->on('data', function ($data) {
  19. echo $data;
  20. });
  21. $connection->on('close', function () {
  22. echo '[CLOSED]' . PHP_EOL;
  23. });
  24. $connection->write("GET / HTTP/1.0\r\nHost: $host\r\n\r\n");
  25. }, function (Exception $e) {
  26. echo 'Error: ' . $e->getMessage() . PHP_EOL;
  27. });