-
-
Notifications
You must be signed in to change notification settings - Fork 143
/
81-server-upgrade-echo.php
62 lines (52 loc) · 1.62 KB
/
81-server-upgrade-echo.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
<?php
/*
Here's the gist to get you started:
$ telnet localhost 1080
> GET / HTTP/1.1
> Upgrade: echo
>
< HTTP/1.1 101 Switching Protocols
< Upgrade: echo
< Connection: upgrade
<
> hello
< hello
> world
< world
*/
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\Loop;
use React\Http\Message\Response;
use React\Stream\ThroughStream;
require __DIR__ . '/../vendor/autoload.php';
// Note how this example uses the `HttpServer` without the `StreamingRequestMiddleware`.
// The initial incoming request does not contain a body and we upgrade to a
// stream object below.
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
if ($request->getHeaderLine('Upgrade') !== 'echo' || $request->getProtocolVersion() === '1.0') {
return new Response(
Response::STATUS_UPGRADE_REQUIRED,
[
'Upgrade' => 'echo'
],
'"Upgrade: echo" required'
);
}
// simply return a duplex ThroughStream here
// it will simply emit any data that is sent to it
// this means that any Upgraded data will simply be sent back to the client
$stream = new ThroughStream();
Loop::addTimer(0, function () use ($stream) {
$stream->write("Hello! Anything you send will be piped back." . PHP_EOL);
});
return new Response(
Response::STATUS_SWITCHING_PROTOCOLS,
[
'Upgrade' => 'echo'
],
$stream
);
});
$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0');
$http->listen($socket);
echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;