-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
23-forward-socket.php
39 lines (30 loc) · 1.26 KB
/
23-forward-socket.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// see also 05-stdio-sockets.php
use React\ChildProcess\Process;
require __DIR__ . '/../vendor/autoload.php';
$server = new React\Socket\Server('127.0.0.1:0');
$server->on('connection', function (React\Socket\ConnectionInterface $connection) {
$connection->on('data', function ($chunk) {
// escape control codes (useful in case encoding or binary data is not working as expected)
// $chunk = addcslashes($chunk,"\0..\37!@\177..\377");
// convert default code page 850 to UTF-8 (German Windows in this case)
$chunk = iconv('CP850','UTF-8', $chunk);
echo $chunk;
});
});
$command = 'php -r "echo 1;sleep(1);echo 2;sleep(1);echo 3;"';
// $command = 'ping google.com';
// $command = 'C:\Windows\System32\ping google.com';
// use stream redirections to consume output of child process in another helper process and forward to socket
$code = '$s=stream_socket_client($argv[1]);do{fwrite($s,$d=fread(STDIN, 8192));}while(isset($d[0]));';
$process = new Process(
$command . ' | php -r ' . escapeshellarg($code) . ' ' . $server->getAddress(),
null,
null,
array()
);
$process->start();
$process->on('exit', function ($code) use ($server) {
$server->close();
echo PHP_EOL . 'Process closed ' . $code . PHP_EOL;
});