asyncclient.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * This example demonstrates the ability for clients to work asynchronously.
  4. *
  5. * By default up to 10 requests will be executed in parallel. HTTP connections
  6. * are re-used and DNS is cached, all thanks to the power of curl.
  7. *
  8. * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/).
  9. * @author Evert Pot (http://evertpot.com/)
  10. * @license http://sabre.io/license/ Modified BSD License
  11. */
  12. use Sabre\HTTP\Client;
  13. use Sabre\HTTP\Request;
  14. // Find the autoloader
  15. $paths = [
  16. __DIR__.'/../vendor/autoload.php',
  17. __DIR__.'/../../../autoload.php',
  18. __DIR__.'/vendor/autoload.php',
  19. ];
  20. foreach ($paths as $path) {
  21. if (file_exists($path)) {
  22. include $path;
  23. break;
  24. }
  25. }
  26. // This is the request we're repeating 1000 times.
  27. $request = new Request('GET', 'http://localhost/');
  28. $client = new Client();
  29. for ($i = 0; $i < 1000; ++$i) {
  30. echo "$i sending\n";
  31. $client->sendAsync(
  32. $request,
  33. // This is the 'success' callback
  34. function ($response) use ($i) {
  35. echo "$i -> ".$response->getStatus()."\n";
  36. },
  37. // This is the 'error' callback. It is called for general connection
  38. // problems (such as not being able to connect to a host, dns errors,
  39. // etc.) and also cases where a response was returned, but it had a
  40. // status code of 400 or higher.
  41. function ($error) use ($i) {
  42. if (Client::STATUS_CURLERROR === $error['status']) {
  43. // Curl errors
  44. echo "$i -> curl error: ".$error['curl_errmsg']."\n";
  45. } else {
  46. // HTTP errors
  47. echo "$i -> ".$error['response']->getStatus()."\n";
  48. }
  49. }
  50. );
  51. }
  52. // After everything is done, we call 'wait'. This causes the client to wait for
  53. // all outstanding http requests to complete.
  54. $client->wait();