forked from reactphp/socket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-benchmark.php
44 lines (33 loc) · 1.31 KB
/
03-benchmark.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
<?php
// Just start the server and connect to it. It will count the number of bytes
// sent for each connection and will print the average throughput once the
// connection closes.
//
// $ php examples/03-benchmark.php 8000
// $ telnet localhost 8000
// $ echo hello world | nc -v localhost 8000
// $ dd if=/dev/zero bs=1M count=1000 | nc -v localhost 8000
use React\EventLoop\Factory;
use React\Socket\Server;
use React\Socket\ConnectionInterface;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
$server = new Server($loop);
$server->listen(isset($argv[1]) ? $argv[1] : 0);
$server->on('connection', function (ConnectionInterface $conn) use ($loop) {
echo '[connected]' . PHP_EOL;
// count the number of bytes received from this connection
$bytes = 0;
$conn->on('data', function ($chunk) use (&$bytes) {
$bytes += strlen($chunk);
});
// report average throughput once client disconnects
$t = microtime(true);
$conn->on('close', function () use ($conn, $t, &$bytes) {
$t = microtime(true) - $t;
echo '[disconnected after receiving ' . $bytes . ' bytes in ' . round($t, 3) . 's => ' . round($bytes / $t / 1024 / 1024, 1) . ' MiB/s]' . PHP_EOL;
});
});
$server->on('error', 'printf');
echo 'bound to ' . $server->getPort() . PHP_EOL;
$loop->run();