-
-
Notifications
You must be signed in to change notification settings - Fork 143
/
82-server-upgrade-chat.php
90 lines (74 loc) · 2.53 KB
/
82-server-upgrade-chat.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/*
Here's the gist to get you started:
$ telnet localhost 1080
> GET / HTTP/1.1
> Upgrade: chat
>
< HTTP/1.1 101 Switching Protocols
< Upgrade: chat
< Connection: upgrade
<
> hello
< user123: hello
> world
< user123: world
Hint: try this with multiple connections :)
*/
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\Loop;
use React\Http\Message\Response;
use React\Stream\CompositeStream;
use React\Stream\ThroughStream;
require __DIR__ . '/../vendor/autoload.php';
// simply use a shared duplex ThroughStream for all clients
// 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
$chat = new ThroughStream();
// 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) use ($chat) {
if ($request->getHeaderLine('Upgrade') !== 'chat' || $request->getProtocolVersion() === '1.0') {
return new Response(
Response::STATUS_UPGRADE_REQUIRED,
[
'Upgrade' => 'chat'
],
'"Upgrade: chat" required'
);
}
// user stream forwards chat data and accepts incoming data
$out = $chat->pipe(new ThroughStream());
$in = new ThroughStream();
$stream = new CompositeStream(
$out,
$in
);
// assign some name for this new connection
$username = 'user' . mt_rand();
// send anything that is received to the whole channel
$in->on('data', function ($data) use ($username, $chat) {
$data = trim(preg_replace('/[^\w \.\,\-\!\?]/u', '', $data));
$chat->write($username . ': ' . $data . PHP_EOL);
});
// say hello to new user
Loop::addTimer(0, function () use ($chat, $username, $out) {
$out->write('Welcome to this chat example, ' . $username . '!' . PHP_EOL);
$chat->write($username . ' joined' . PHP_EOL);
});
// send goodbye to channel once connection closes
$stream->on('close', function () use ($username, $chat) {
$chat->write($username . ' left' . PHP_EOL);
});
return new Response(
Response::STATUS_SWITCHING_PROTOCOLS,
[
'Upgrade' => 'chat'
],
$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;