random_client.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * Websocket client that read/write random data.
  4. * Run in console: php examples/random_client.php
  5. *
  6. * Console options:
  7. * --uri <uri> : The URI to connect to, default ws://localhost:8000
  8. * --timeout <int> : Timeout in seconds, random default
  9. * --fragment_size <int> : Fragment size as bytes, random default
  10. * --debug : Output log data (if logger is available)
  11. */
  12. namespace WebSocket;
  13. require __DIR__ . '/../vendor/autoload.php';
  14. error_reporting(-1);
  15. $randStr = function (int $maxlength = 4096) {
  16. $string = '';
  17. $length = rand(1, $maxlength);
  18. for ($i = 0; $i < $length; $i++) {
  19. $string .= chr(rand(33, 126));
  20. }
  21. return $string;
  22. };
  23. echo "> Random client\n";
  24. // Server options specified or random
  25. $options = array_merge([
  26. 'uri' => 'ws://localhost:8000',
  27. 'timeout' => rand(1, 60),
  28. 'fragment_size' => rand(1, 4096) * 8,
  29. ], getopt('', ['uri:', 'timeout:', 'fragment_size:', 'debug']));
  30. // If debug mode and logger is available
  31. if (isset($options['debug']) && class_exists('WebSocket\EchoLog')) {
  32. $logger = new EchoLog();
  33. $options['logger'] = $logger;
  34. echo "> Using logger\n";
  35. }
  36. // Main loop
  37. while (true) {
  38. try {
  39. $client = new Client($options['uri'], $options);
  40. $info = json_encode([
  41. 'uri' => $options['uri'],
  42. 'timeout' => $options['timeout'],
  43. 'framgemt_size' => $client->getFragmentSize(),
  44. ]);
  45. echo "> Creating client {$info}\n";
  46. try {
  47. while (true) {
  48. // Random actions
  49. switch (rand(1, 10)) {
  50. case 1:
  51. echo "> Sending text\n";
  52. $client->text("Text message {$randStr()}");
  53. break;
  54. case 2:
  55. echo "> Sending binary\n";
  56. $client->binary("Binary message {$randStr()}");
  57. break;
  58. case 3:
  59. echo "> Sending close\n";
  60. $client->close(rand(1000, 2000), "Close message {$randStr(8)}");
  61. break;
  62. case 4:
  63. echo "> Sending ping\n";
  64. $client->ping("Ping message {$randStr(8)}");
  65. break;
  66. case 5:
  67. echo "> Sending pong\n";
  68. $client->pong("Pong message {$randStr(8)}");
  69. break;
  70. default:
  71. echo "> Receiving\n";
  72. $received = $client->receive();
  73. echo "> Received {$client->getLastOpcode()}: {$received}\n";
  74. }
  75. sleep(rand(1, 5));
  76. }
  77. } catch (\Throwable $e) {
  78. echo "ERROR I/O: {$e->getMessage()} [{$e->getCode()}]\n";
  79. }
  80. } catch (\Throwable $e) {
  81. echo "ERROR: {$e->getMessage()} [{$e->getCode()}]\n";
  82. }
  83. sleep(rand(1, 5));
  84. }