forked from reactphp-legacy/socket-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path03-netcat.php
60 lines (45 loc) · 1.63 KB
/
03-netcat.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
use React\EventLoop\Factory;
use React\SocketClient\TcpConnector;
use React\SocketClient\DnsConnector;
use React\SocketClient\TimeoutConnector;
use React\SocketClient\ConnectionInterface;
require __DIR__ . '/../vendor/autoload.php';
if (!isset($argv[2])) {
fwrite(STDERR, 'Usage error: required arguments <host> <port>' . PHP_EOL);
exit(1);
}
$loop = Factory::create();
$factory = new \React\Dns\Resolver\Factory();
$resolver = $factory->create('8.8.8.8', $loop);
$tcp = new TcpConnector($loop);
$dns = new DnsConnector($tcp, $resolver);
// time out connection attempt in 3.0s
$dns = new TimeoutConnector($dns, 3.0, $loop);
$stdin = new Stream(STDIN, $loop);
$stdin->pause();
$stdout = new Stream(STDOUT, $loop);
$stdout->pause();
$stderr = new Stream(STDERR, $loop);
$stderr->pause();
$stderr->write('Connecting' . PHP_EOL);
$dns->create($argv[1], $argv[2])->then(function (ConnectionInterface $connection) use ($stdin, $stdout, $stderr) {
// pipe everything from STDIN into connection
$stdin->resume();
$stdin->pipe($connection);
// pipe everything from connection to STDOUT
$connection->pipe($stdout);
// report errors to STDERR
$connection->on('error', function ($error) use ($stderr) {
$stderr->write('Stream ERROR: ' . $error . PHP_EOL);
});
// report closing and stop reading from input
$connection->on('close', function () use ($stderr, $stdin) {
$stderr->write('[CLOSED]' . PHP_EOL);
$stdin->close();
});
$stderr->write('Connected' . PHP_EOL);
}, function ($error) use ($stderr) {
$stderr->write('Connection ERROR: ' . $error . PHP_EOL);
});
$loop->run();