fork download
  1. <?php
  2.  
  3. if ( !$s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) ) {
  4. throw new Exception('socket_create failed: ' . socket_strerror(socket_last_error()) );
  5. }
  6.  
  7. // $ip = gethostbyname('ya.ru');
  8. $ip = '127.0.0.1';
  9. $port = 8123;
  10. $useNoBlock = in_array('--no-block', $argv);
  11. $isFailtTest = in_array('--fail', $argv);
  12.  
  13. if ($isFailtTest) {
  14. $ip = gethostbyname('ya.ru');
  15. $port = 80;
  16. echo "Please disconnect LAN after connect\n";
  17. }
  18.  
  19. echo "Connect to $ip:$port\n";
  20.  
  21. if ($useNoBlock) {
  22. }
  23.  
  24. if ( !socket_connect($s, $ip, $port) ) {
  25. if (!canIgnoreError($useNoBlock)) {
  26. throw new Exception('failed: ' . socket_strerror(socket_last_error()) );
  27. } else {
  28. printf("connect: Ignore error %s\n", socket_last_error());
  29. }
  30. }
  31.  
  32. while (true) {
  33.  
  34. if ($useNoBlock) {
  35. waitFor($s);
  36. }
  37.  
  38. usleep(100000);
  39.  
  40. $data = socket_read($s, 1000);
  41. if ($data === false) {
  42. if (!canIgnoreError($useNoBlock)) {
  43. throw new \Exception("read: " . socket_strerror(socket_last_error()));
  44. } else {
  45. echo "read: Ignore error " . socket_last_error() . "\n";
  46. continue;
  47. }
  48. }
  49. printf("Read %d bytes\n", strlen($data));
  50. echo "> " . $data . "\n";
  51. }
  52.  
  53. echo "EOF or error\n";
  54.  
  55. function waitFor($s)
  56. {
  57. $read = [$s];
  58. $write = [$s];
  59. $except = [$s];
  60.  
  61. echo "Wait ...\n";
  62. $r = socket_select($read, $write, $except, null);
  63. assert($r !== false);
  64. if ($read) {
  65. echo "Read event\n";
  66. }
  67. if ($write) {
  68. echo "Write event\n";
  69. }
  70. if ($except) {
  71. echo "Except event\n";
  72. }
  73. }
  74.  
  75. /**
  76.  * Можно ли игнорировать ошибку вроде SOCKET_EWOULDBLOCK
  77.  */
  78. function canIgnoreError($useNoBlock)
  79. {
  80. if (!$useNoBlock) {
  81. return;
  82. }
  83.  
  84. if (defined('SOCKET_EAGAIN') && $e == SOCKET_EAGAIN) {
  85. return true;
  86. }
  87.  
  88. return in_array($e, [SOCKET_EWOULDBLOCK, SOCKET_EINPROGRESS]);
  89. }
  90.  
  91.  
  92.  
  93.  
Runtime error #stdin #stdout #stderr 0.02s 52472KB
stdin
Standard input is empty
stdout
Connect to 127.0.0.1:8123
stderr
PHP Warning:  socket_connect(): unable to connect [101]: Network is unreachable in /home/Uy7Ovi/prog.php on line 25
PHP Fatal error:  Uncaught exception 'Exception' with message 'failed: Network is unreachable' in /home/Uy7Ovi/prog.php:27
Stack trace:
#0 {main}
  thrown in /home/Uy7Ovi/prog.php on line 27