21-netcat-client.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. // Simple plaintext TCP/IP and secure TLS client example that pipes console I/O.
  3. // This shows how a plaintext TCP/IP or secure TLS connection is established and
  4. // then everything you type on STDIN will be sent and everything the server
  5. // sends will be piped to your STDOUT.
  6. //
  7. // $ php examples/21-netcat-client.php www.google.com:80
  8. // $ php examples/21-netcat-client.php tls://www.google.com:443
  9. use React\Socket\Connector;
  10. use React\Socket\ConnectionInterface;
  11. use React\Stream\ReadableResourceStream;
  12. use React\Stream\WritableResourceStream;
  13. require __DIR__ . '/../vendor/autoload.php';
  14. if (!defined('STDIN')) {
  15. echo 'STDIO streams require CLI SAPI' . PHP_EOL;
  16. exit(1);
  17. }
  18. if (DIRECTORY_SEPARATOR === '\\') {
  19. fwrite(STDERR, 'Non-blocking console I/O not supported on Microsoft Windows' . PHP_EOL);
  20. exit(1);
  21. }
  22. if (!isset($argv[1])) {
  23. fwrite(STDERR, 'Usage error: required argument <host:port>' . PHP_EOL);
  24. exit(1);
  25. }
  26. $connector = new Connector();
  27. $stdin = new ReadableResourceStream(STDIN);
  28. $stdin->pause();
  29. $stdout = new WritableResourceStream(STDOUT);
  30. $stderr = new WritableResourceStream(STDERR);
  31. $stderr->write('Connecting' . PHP_EOL);
  32. $connector->connect($argv[1])->then(function (ConnectionInterface $connection) use ($stdin, $stdout, $stderr) {
  33. // pipe everything from STDIN into connection
  34. $stdin->resume();
  35. $stdin->pipe($connection);
  36. // pipe everything from connection to STDOUT
  37. $connection->pipe($stdout);
  38. // report errors to STDERR
  39. $connection->on('error', function (Exception $e) use ($stderr) {
  40. $stderr->write('Stream error: ' . $e->getMessage() . PHP_EOL);
  41. });
  42. // report closing and stop reading from input
  43. $connection->on('close', function () use ($stderr, $stdin) {
  44. $stderr->write('[CLOSED]' . PHP_EOL);
  45. $stdin->close();
  46. });
  47. $stderr->write('Connected' . PHP_EOL);
  48. }, function (Exception $e) use ($stderr) {
  49. $stderr->write('Connection error: ' . $e->getMessage() . PHP_EOL);
  50. });