1 | 2 | simandl | <?php |
2 | | | |
3 | | | namespace Phem\Libraries\MessageBus; |
4 | | | |
5 | | | use Exception; |
6 | | | use Phem\Core\Collection; |
7 | | | use Ratchet\ConnectionInterface; |
8 | | | use Ratchet\MessageComponentInterface; |
9 | | | |
10 | | | /** |
11 | | | * @author Jakub PetrĹžĂlka <petrzilka@czweb.net> |
12 | | | */ |
13 | | | class MessageBus implements MessageComponentInterface |
14 | | | { |
15 | | | |
16 | | | protected $clients; |
17 | | | |
18 | | | public function __construct() |
19 | | | { |
20 | | | $this->clients = new Collection(); |
21 | | | } |
22 | | | |
23 | | | public function onOpen(ConnectionInterface $conn) |
24 | | | { |
25 | | | // Store the new connection to send messages to later |
26 | | | $this->clients->put($conn->resourceId, $conn); |
27 | | | |
28 | | | echo "New connection! ({$conn->resourceId})\n"; |
29 | | | |
30 | | | $client = $this->clients->get($conn->resourceId); |
31 | | | //$client->send('{"acceptedConnection":"'.$conn->resourceId.'"}'); |
32 | | | |
33 | | | return true; |
34 | | | } |
35 | | | |
36 | | | public function onNotify($msg) |
37 | | | { |
38 | | | foreach ($this->clients as $client) |
39 | | | { |
40 | | | $client->send($msg); |
41 | | | } |
42 | | | } |
43 | | | |
44 | | | public function onMessage(ConnectionInterface $from, $msg) |
45 | | | { |
46 | | | $msgobj = json_decode($msg); |
47 | | | |
48 | | | foreach ($this->clients as $client) |
49 | | | { |
50 | | | $client->send($msg); |
51 | | | } |
52 | | | } |
53 | | | |
54 | | | public function onClose(ConnectionInterface $conn) |
55 | | | { |
56 | | | \Phem\Environment\Application::onConnectionClose($conn->resourceId); |
57 | | | |
58 | | | // The connection is closed, remove it, as we can no longer send it messages |
59 | | | $this->clients->removeKey($conn->resourceId); |
60 | | | |
61 | | | echo "Connection {$conn->resourceId} has disconnected\n"; |
62 | | | } |
63 | | | |
64 | | | public function onError(ConnectionInterface $conn, Exception $e) |
65 | | | { |
66 | | | echo "An error has occurred: {$e->getMessage()}\n"; |
67 | | | |
68 | | | $conn->close(); |
69 | | | } |
70 | | | |
71 | | | } |