-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy path03-redis-subscribe.php
More file actions
66 lines (51 loc) · 1.97 KB
/
03-redis-subscribe.php
File metadata and controls
66 lines (51 loc) · 1.97 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
59
60
61
62
63
64
65
66
<?php
require __DIR__ . '/../vendor/autoload.php';
use Clue\React\Redis\Factory;
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
);
});
$red = isset($argv[2]) ? $argv[2] : 'channel';
$factory = new Factory($loop);
$factory->createClient("localhost")->then(function (Clue\React\Redis\Client $client) use ($channel, $red) {
$client->on('message', function ($topic, $message) use ($channel) {
$channel->writeMessage($message);
});
return $client->subscribe($red);
})->then(null, function ($e) {
echo 'ERROR: Unable to subscribe to Redis channel: ' . $e;
});
$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 Redis PubSub channel "' . $red . '" (channel is second parameter)' . PHP_EOL;
$loop->run();