-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebsocket.php
More file actions
52 lines (42 loc) · 1.34 KB
/
Websocket.php
File metadata and controls
52 lines (42 loc) · 1.34 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
<?php
namespace RollandRock\WebsocketBundle;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
use RollandRock\WebsocketBundle\Client\ClientStack;
use RollandRock\WebsocketBundle\Handler\HandlerRegistry;
/**
* @author Pierre Rolland <roll.pierre@gmail.com>
*/
class Websocket implements MessageComponentInterface
{
/** @var ClientStack */
private $clientStack;
/** @var HandlerRegistry */
private $handlerRegistry;
/** @var string */
private $clientClass;
public function __construct(HandlerRegistry $handlerRegistry, string $clientClass)
{
$this->clientStack = new ClientStack();
$this->handlerRegistry = $handlerRegistry;
$this->clientClass = $clientClass;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clientStack->addClient(new ${$this->clientClass}($conn));
}
public function onMessage(ConnectionInterface $from, $msg)
{
$msg = json_decode($msg, true);
$this->handlerRegistry->getHandler($msg['type'])->handle($this->clientStack, $from, $msg['data']);
}
public function onClose(ConnectionInterface $conn)
{
$this->clientStack->removeClient($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
$this->onClose($conn);
$conn->close();
}
}