-
Notifications
You must be signed in to change notification settings - Fork 1
/
Server.php
114 lines (93 loc) · 3.05 KB
/
Server.php
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace T4web\Websocket;
use SplObjectStorage;
use Exception;
use Zend\EventManager\EventManager;
use Zend\ServiceManager\ServiceLocatorInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Server implements MessageComponentInterface
{
/**
* @var SplObjectStorage
*/
private $connections;
/**
* @var ServiceLocatorInterface
*/
private $serviceLocator;
/**
* @var array
*/
private $handlers;
/**
* @var bool
*/
private $isDebugEnabled;
public function __construct(
ServiceLocatorInterface $serviceLocator,
array $eventHandlers,
$isDebugEnabled = false
)
{
$this->connections = new SplObjectStorage();
$this->serviceLocator = $serviceLocator;
$this->handlers = $eventHandlers;
$this->isDebugEnabled = $isDebugEnabled;
}
/**
* @param ConnectionInterface $connection
*/
public function onOpen(ConnectionInterface $connection)
{
$this->connections->attach($connection);
$this->debug('New client connected');
}
public function onMessage(ConnectionInterface $connection, $messageAsJson)
{
$message = json_decode($messageAsJson, true);
$this->debug('Income message: ' . var_export($message, true));
if (!isset($message['event']) || !isset($this->handlers[$message['event']])) {
$response = [
'event' => 'unknownEvent',
'data' => null,
'error' => 'event ' . @$message['event'] . ' not described',
];
$this->debug('Send message: ' . var_export($response, true));
$connection->send(json_encode($response));
return;
}
/** @var Handler\HandlerInterface $handler */
$handler = $this->serviceLocator->get($this->handlers[$message['event']]);
if (!($handler instanceof Handler\HandlerInterface)) {
$response = [
'event' => 'unknownEvent',
'data' => null,
'error' => 'handler for event ' . $message['event'] . ' must be instance of T4web\Websocket\Handler\HandlerInterface',
];
$this->debug('Send message: ' . var_export($response, true));
$connection->send(json_encode($response));
return;
}
$handler->handle($message['event'], $message['data'], $connection, $this->connections);
return;
}
public function onClose(ConnectionInterface $connection)
{
$this->debug('Client close connection');
if (!isset($this->connections[$connection])) {
return;
}
$this->connections->detach($connection);
}
public function onError(ConnectionInterface $connection, Exception $e) {
$this->debug('Client error: '. $e->getMessage());
$connection->close();
}
private function debug($msg, $prefix = "**Debug: ")
{
if ($this->isDebugEnabled) {
echo $prefix . $msg . PHP_EOL;
}
}
}