-
-
Notifications
You must be signed in to change notification settings - Fork 157
/
21-netcat-client.php
64 lines (50 loc) · 1.97 KB
/
21-netcat-client.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
61
62
63
64
<?php
// Simple plaintext TCP/IP and secure TLS client example that pipes console I/O.
// This shows how a plaintext TCP/IP or secure TLS connection is established and
// then everything you type on STDIN will be sent and everything the server
// sends will be piped to your STDOUT.
//
// $ php examples/21-netcat-client.php www.google.com:80
// $ php examples/21-netcat-client.php tls://www.google.com:443
use React\Socket\Connector;
use React\Socket\ConnectionInterface;
use React\Stream\ReadableResourceStream;
use React\Stream\WritableResourceStream;
require __DIR__ . '/../vendor/autoload.php';
if (!defined('STDIN')) {
echo 'STDIO streams require CLI SAPI' . PHP_EOL;
exit(1);
}
if (DIRECTORY_SEPARATOR === '\\') {
fwrite(STDERR, 'Non-blocking console I/O not supported on Microsoft Windows' . PHP_EOL);
exit(1);
}
if (!isset($argv[1])) {
fwrite(STDERR, 'Usage error: required argument <host:port>' . PHP_EOL);
exit(1);
}
$connector = new Connector();
$stdin = new ReadableResourceStream(STDIN);
$stdin->pause();
$stdout = new WritableResourceStream(STDOUT);
$stderr = new WritableResourceStream(STDERR);
$stderr->write('Connecting' . PHP_EOL);
$connector->connect($argv[1])->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 (Exception $e) use ($stderr) {
$stderr->write('Stream error: ' . $e->getMessage() . 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 (Exception $e) use ($stderr) {
$stderr->write('Connection error: ' . $e->getMessage() . PHP_EOL);
});