-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.php
More file actions
228 lines (205 loc) · 8.37 KB
/
server.php
File metadata and controls
228 lines (205 loc) · 8.37 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
use \WebSocket\Throwable;
use \WebSocket\Exception\ExceptionInterface;
use \WebSocket\Message\{
Binary,
Close,
Ping,
Pong,
Text,
};
use \WebSocket\Middleware\{
CloseHandler,
CompressionExtension,
PingResponder,
};
use \WebSocket\Middleware\CompressionExtension\DeflateCompressor;
use \WebSocket\Test\EchoLog;
require dirname(dirname( __FILE__ )) . '/vendor/autoload.php';
$options = [
"port" => 8080,
"ssl" => true,
"timeout" => "60",
"framesize" => "4096",
"connections" => 30,
"debug" => false,
"deflate" => false
];
class SolidPubSub {
private $options;
private $clients;
private $subscriptions;
public function __construct($options) {
$this->options = $options;
$this->clients = [];
$this->subscriptions = [];
$this->server = $this->createServer();
}
public function onHandshake(
\WebSocket\Server $server,
\WebSocket\Connection $connection,
$request,
$response
) {
// Store the new connection in $this->clients
$this->clients[$connection->getRemoteName()] = $connection;
echo "> [{$connection->getRemoteName()}] Client connected {$request->getUri()}\n";
}
public function onText(
\WebSocket\Server $server,
\WebSocket\Connection $connection,
\WebSocket\Message\Text $message
) {
echo "> [{$connection->getRemoteName()}] Received [{$message->getOpcode()}]\n";
$messageInfo = explode(" ", $message->getContent(), 2);
$command = $messageInfo[0];
$body = trim($messageInfo[1]);
switch ($command) {
case "auth":
case "dpop":
// FIXME: we should check that the client is allowed to listen
break;
case "sub":
echo "Client sub for $body\n";
if (!isset($this->subscriptions[$body])) {
$this->subscriptions[$body] = array();
}
$this->subscriptions[$body][] = $connection;
$connection->send(new \WebSocket\Message\Text("ack $body"));
break;
case "pub":
echo "Client pub for $body\n";
if (isset($this->subscriptions[$body])) {
foreach ( $this->subscriptions[$body] as $client ) {
try {
$client->send(new \WebSocket\Message\Text("pub $body"));
} catch (\Throwable $e) {
echo "> ERROR SENDING: {$e->getMessage()}\n";
}
}
}
break;
default:
echo "Client " . $connection->getRemoteName() . " said $message\n";
foreach ( $this->clients as $client ) {
if ( $connection->getRemoteName() == $client->getRemoteName() ) {
continue;
}
try {
$client->send(new \WebSocket\Message\Text("Client " . $connection->getRemoteName() . " said $message\n"));
} catch (\Throwable $e) {
echo "> ERROR SENDING: {$e->getMessage()}\n";
}
}
break;
}
}
public function onClose(
\WebSocket\Server $server,
\WebSocket\Connection $connection,
\WebSocket\Message\Close $message
) {
echo "Client " . $connection->getRemoteName() . " left\n";
foreach ($this->subscriptions as $url => $subscribers) {
foreach ($subscribers as $key => $client) {
if ($client->getRemoteName() == $connection->getRemoteName()) {
echo "Removing subscription for $url\n";
unset($subscribers[$url][$key]);
}
}
}
}
public function onDisconnect(
\WebSocket\Server $server,
\WebSocket\Connection $connection
) {
echo "Client " . $connection->getRemoteName() . " disconnected\n";
foreach ($this->subscriptions as $url => $subscribers) {
foreach ($subscribers as $key => $client) {
if ($client->getRemoteName() == $connection->getRemoteName()) {
echo "Removing subscription for $url\n";
unset($subscribers[$url][$key]);
}
}
}
}
public function onError(
\WebSocket\Server $server,
\WebSocket\Connection|null $connection,
ExceptionInterface $exception
) {
$name = $connection ? "[{$connection->getRemoteName()}]" : "[-]";
echo "> {$name} Error: {$exception->getMessage()}\n";
echo "Client " . $connection->getRemoteName() . " errored - disconnecting\n";
foreach ($this->subscriptions as $url => $subscribers) {
foreach ($subscribers as $key => $client) {
if ($client->getRemoteName() == $connection->getRemoteName()) {
echo "Removing subscription for $url\n";
unset($subscribers[$url][$key]);
}
}
}
}
public function createServer() {
// Initiate server.
try {
$server = new \WebSocket\Server(
$this->options['port'] ?? 8080,
$this->options['ssl'] ?? true
);
// Set up SSL with CA certificate
$server->setContext(['ssl' => [
'local_cert' => 'certs/server.crt',
'local_pk' => 'certs/server.key',
'verify_peer' => false, // if false, accept SSL handshake without client certificate
'verify_peer_name' => false,
'allow_self_signed' => true,
]]);
$server
->addMiddleware(new CloseHandler())
->addMiddleware(new PingResponder())
;
// If debug mode and logger is available
if (($this->options['debug'] ?? false) && class_exists('WebSocket\Test\EchoLog')) {
$server->setLogger(new EchoLog());
echo "# Using logger\n";
}
$server->setTimeout($this->options['timeout'] ?? 60);
echo "# Set timeout: {$this->options['timeout']}\n";
$server->setFrameSize($this->options['framesize'] ?? 4096);
echo "# Set frame size: {$this->options['framesize']}\n";
$server->setMaxConnections($this->options['connections'] ?? 30);
echo "# Set max connections: {$this->options['connections']}\n";
if ($this->options['deflate'] ?? false) {
$server->addMiddleware(new CompressionExtension(new DeflateCompressor()));
echo "# Using per-message: deflate compression\n";
}
$server->addMiddleware(new WebSocket\Middleware\SubprotocolNegotiation([
'solid-0.1'
]));
echo "# Added subprotocol solid-0.1\n";
echo "# Listening on port {$server->getPort()}\n";
// Wiring the server handlers to our handlers;
$server
->onHandshake(function (\WebSocket\Server $server, \WebSocket\Connection $connection, $request, $response) {
return $this->onHandshake($server, $connection, $request, $response);
})
->onDisconnect(function(\WebSocket\Server $server, \WebSocket\Connection $connection) {
return $this->onDisconnect($server, $connection);
})
->onText(function(\WebSocket\Server $server, \WebSocket\Connection $connection, \WebSocket\Message\Text $message) {
return $this->onText($server, $connection, $message);
})
->onClose(function(\WebSocket\Server $server, \WebSocket\Connection $connection, \WebSocket\Message\Close $message) {
return $this->onClose($server, $connection, $message);
})
->onError(function (\WebSocket\Server $server, \WebSocket\Connection|null $connection, ExceptionInterface $exception) {
return $this->onError($server, $connection, $exception);
})
->start();
} catch (\Throwable $e) {
echo "> ERROR: {$e->getMessage()}\n";
}
}
}
$server = new SolidPubSub($options);