|
| 1 | +<?php |
| 2 | + |
| 3 | +use React\EventLoop\Factory; |
| 4 | + |
| 5 | +require __DIR__ . '/../vendor/autoload.php'; |
| 6 | + |
| 7 | +$loop = Factory::create(); |
| 8 | + |
| 9 | +// resolve hostname before establishing TCP/IP connection (resolving DNS is still blocking here) |
| 10 | +// for illustration purposes only, should use react/socket or react/dns instead! |
| 11 | +$ip = gethostbyname('www.google.com'); |
| 12 | +if (ip2long($ip) === false) { |
| 13 | + echo 'Unable to resolve hostname' . PHP_EOL; |
| 14 | + exit(1); |
| 15 | +} |
| 16 | + |
| 17 | +// establish TCP/IP connection (non-blocking) |
| 18 | +// for illustraction purposes only, should use react/socket instead! |
| 19 | +$stream = stream_socket_client('tcp://' . $ip . ':80', $errno, $errstr, null, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT); |
| 20 | +if (!$stream) { |
| 21 | + exit(1); |
| 22 | +} |
| 23 | +stream_set_blocking($stream, false); |
| 24 | + |
| 25 | +// print progress every 10ms |
| 26 | +echo 'Connecting'; |
| 27 | +$timer = $loop->addPeriodicTimer(0.01, function () { |
| 28 | + echo '.'; |
| 29 | +}); |
| 30 | + |
| 31 | +// wait for connection success/error |
| 32 | +$loop->addWriteStream($stream, function ($stream) use ($loop, $timer) { |
| 33 | + $loop->removeWriteStream($stream); |
| 34 | + $loop->cancelTimer($timer); |
| 35 | + |
| 36 | + // check for socket error (connection rejected) |
| 37 | + if (stream_socket_get_name($stream, true) === false) { |
| 38 | + echo '[unable to connect]' . PHP_EOL; |
| 39 | + exit(1); |
| 40 | + } else { |
| 41 | + echo '[connected]' . PHP_EOL; |
| 42 | + } |
| 43 | + |
| 44 | + // send HTTP request |
| 45 | + fwrite($stream, "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"); |
| 46 | + |
| 47 | + // wait for HTTP response |
| 48 | + $loop->addReadStream($stream, function ($stream) use ($loop) { |
| 49 | + $chunk = fread($stream, 64 * 1024); |
| 50 | + |
| 51 | + // reading nothing means we reached EOF |
| 52 | + if ($chunk === '') { |
| 53 | + echo '[END]' . PHP_EOL; |
| 54 | + $loop->removeReadStream($stream); |
| 55 | + fclose($stream); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + echo $chunk; |
| 60 | + }); |
| 61 | +}); |
| 62 | + |
| 63 | +$loop->run(); |
0 commit comments