send.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * Simple send & receive client for test purpose.
  4. * Run in console: php examples/send.php <options> <message>
  5. *
  6. * Console options:
  7. * --uri <uri> : The URI to connect to, default ws://localhost:8000
  8. * --opcode <string> : Opcode to send, default 'text'
  9. * --debug : Output log data (if logger is available)
  10. */
  11. namespace WebSocket;
  12. require __DIR__ . '/../vendor/autoload.php';
  13. error_reporting(-1);
  14. echo "> Send client\n";
  15. // Server options specified or random
  16. $options = array_merge([
  17. 'uri' => 'ws://localhost:8000',
  18. 'opcode' => 'text',
  19. ], getopt('', ['uri:', 'opcode:', 'debug']));
  20. $message = array_pop($argv);
  21. // If debug mode and logger is available
  22. if (isset($options['debug']) && class_exists('WebSocket\EchoLog')) {
  23. $logger = new EchoLog();
  24. $options['logger'] = $logger;
  25. echo "> Using logger\n";
  26. }
  27. try {
  28. // Create client, send and recevie
  29. $client = new Client($options['uri'], $options);
  30. $client->send($message, $options['opcode']);
  31. echo "> Sent '{$message}' [opcode: {$options['opcode']}]\n";
  32. if (in_array($options['opcode'], ['text', 'binary'])) {
  33. $message = $client->receive();
  34. $opcode = $client->getLastOpcode();
  35. if (!is_null($message)) {
  36. echo "> Got '{$message}' [opcode: {$opcode}]\n";
  37. }
  38. }
  39. $client->close();
  40. echo "> Closing client\n";
  41. } catch (\Throwable $e) {
  42. echo "ERROR: {$e->getMessage()} [{$e->getCode()}]\n";
  43. }