-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy path02-plaintext-chat.php
70 lines (53 loc) · 2.04 KB
/
02-plaintext-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
<?php
require __DIR__ . '/../vendor/autoload.php';
use Clue\React\Sse\BufferedChannel;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
use React\Socket\TcpConnector;
use React\Stream\ThroughStream;
$loop = React\EventLoop\Factory::create();
$channel = new BufferedChannel();
$http = new React\Http\Server($loop, function (ServerRequestInterface $request) use ($channel, $loop) {
if ($request->getUri()->getPath() === '/') {
return new Response(
200,
array('Content-Type' => 'text/html'),
file_get_contents(__DIR__ . '/00-eventsource.html')
);
}
if ($request->getUri()->getPath() !== '/demo') {
return new Response(404);
}
echo 'connected' . PHP_EOL;
$stream = new ThroughStream();
$id = $request->getHeaderLine('Last-Event-ID');
$loop->futureTick(function () use ($channel, $stream, $id) {
$channel->connect($stream, $id);
});
$stream->on('close', function () use ($stream, $channel) {
echo 'disconnected' . PHP_EOL;
$channel->disconnect($stream);
});
return new Response(
200,
array('Content-Type' => 'text/event-stream'),
$stream
);
});
$port = isset($argv[2]) ? $argv[2] : 8000;
$connector = new TcpConnector($loop);
$connector->connect('127.0.0.1:' . $port)->then(function (React\Socket\ConnectionInterface $stream) use ($channel) {
$buffer = '';
$stream->on('data', function ($data) use (&$buffer, $channel) {
$buffer .= $data;
while (($pos = strpos($buffer, "\n")) !== false) {
$channel->writeMessage(substr($buffer, 0, $pos));
$buffer = substr($buffer, $pos + 1);
}
});
}, 'printf');
$socket = new \React\Socket\Server(isset($argv[1]) ? '0.0.0.0:' . $argv[1] : '0.0.0.0:0', $loop);
$http->listen($socket);
echo 'Server now listening on ' . $socket->getAddress() . ' (port is first parameter)' . PHP_EOL;
echo 'Connecting to plain text chat on port ' . $port . ' (port is second parameter)' . PHP_EOL;
$loop->run();