13-http-client-blocking.php 753 B

12345678910111213141516171819202122232425262728293031
  1. <?php
  2. use React\EventLoop\Loop;
  3. require __DIR__ . '/../vendor/autoload.php';
  4. // connect to example.com:80 (blocking call!)
  5. // for illustration purposes only, should use react/socket instead
  6. $stream = stream_socket_client('tcp://example.com:80');
  7. if (!$stream) {
  8. exit(1);
  9. }
  10. stream_set_blocking($stream, false);
  11. // send HTTP request
  12. fwrite($stream, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");
  13. // wait for HTTP response
  14. Loop::addReadStream($stream, function ($stream) {
  15. $chunk = fread($stream, 64 * 1024);
  16. // reading nothing means we reached EOF
  17. if ($chunk === '') {
  18. echo '[END]' . PHP_EOL;
  19. Loop::removeReadStream($stream);
  20. fclose($stream);
  21. return;
  22. }
  23. echo $chunk;
  24. });