-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathws-server.php
More file actions
71 lines (56 loc) · 1.48 KB
/
ws-server.php
File metadata and controls
71 lines (56 loc) · 1.48 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
67
68
69
70
71
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require __DIR__ . '/vendor/autoload.php';
class NotificationServer implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg)
{
// Optionally handle messages from clients
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
$conn->close();
}
public function broadcast($msg)
{
foreach ($this->clients as $client)
{
$client->send($msg);
}
}
}
$notificationServer = new NotificationServer();
$loop = React\EventLoop\Loop::get();
$redisUrl = getenv('REDIS_URL') ?: 'redis://redis:6379';
$factory = new Clue\React\Redis\Factory($loop);
$factory->createClient('redis://redis:6379')->then(function (Clue\React\Redis\Client $client) use ($notificationServer)
{
$client->subscribe('notifications');
$client->on('message', function ($channel, $payload) use ($notificationServer)
{
$notificationServer->broadcast($payload);
});
});
$webSock = new React\Socket\SocketServer('0.0.0.0:8081', [], $loop);
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer($notificationServer)
),
$webSock,
$loop
);
$loop->run();