-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy path01-simple-periodic.php
More file actions
58 lines (43 loc) · 1.59 KB
/
01-simple-periodic.php
File metadata and controls
58 lines (43 loc) · 1.59 KB
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
<?php
require __DIR__ . '/../vendor/autoload.php';
use Clue\React\Sse\BufferedChannel;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
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
);
});
$socket = new \React\Socket\Server(isset($argv[1]) ? '0.0.0.0:' . $argv[1] : '0.0.0.0:0', $loop);
$http->listen($socket);
$loop->addPeriodicTimer(2.0, function () use ($channel) {
$channel->writeMessage('ticking ' . mt_rand(1, 5) . '...');
});
echo 'Server now listening on ' . $socket->getAddress() . ' (port is first parameter)' . PHP_EOL;
echo 'This will send a message every 2 seconds' . PHP_EOL;
$loop->run();