forked from Ahmard/reactphp-live-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPublicChatServer.php
More file actions
167 lines (135 loc) · 5.42 KB
/
PublicChatServer.php
File metadata and controls
167 lines (135 loc) · 5.42 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
<?php
namespace App\Servers\Socket;
use App\Core\Servers\SocketServer;
use App\Core\Servers\SocketServerInterface;
use App\Core\Socket\Colis\Dispatcher;
use App\Core\Socket\Colis\Matcher;
use App\Core\Socket\ConnectionInterface;
use App\Core\Socket\Payload;
use App\Core\Socket\Request;
use Exception;
use React\EventLoop\TimerInterface;
use SplObjectStorage;
use Throwable;
class PublicChatServer extends SocketServer implements SocketServerInterface
{
public array $colis;
public string $prefix;
protected SplObjectStorage $connections;
protected ConnectionInterface $currClient;
protected array $lastUnansweredPings = [];
public function __construct(array $colis)
{
$this->prefix = $_ENV['PUBLIC_CHAT_SOCKET_URL_PREFIX'];
$this->colis = $colis;
$this->connections = clientStorage();
$this->monitorClients();
}
public function monitorClients()
{
event()->on('system.pong', function ($connection) {
unset($this->lastUnansweredPings[$connection->getConnectionId()]);
});
if ($_ENV['WILL_PING_CLIENTS'] == 'true') {
setInterval($_ENV['CLIENT_PING_INTERVAL'], function () {
static $loop = 1;
$totalClients = count($this->connections);
$this->write(
"\n[#] Pinging {$totalClients} clients: #round {$loop}",
$_ENV['SHOW_CLIENT_PING_MESSAGE']
);
foreach (clientStorage() as $connection) {
//Check if current client does not reply our last pinging
$connectionExists = $this->lastUnansweredPings[$connection->getConnectionId()] ?? false;
if ($connectionExists) {
$this->write("\n\n" . date('H:i:s'), $_ENV['SHOW_CLIENT_PING_MESSAGE']);
$this->write(
color("\n -> Connection({$connection->getConnectionId()}) failed to reply its last ping, so it has been disconnected.\n")
->fg('light_red')
);
$this->closeAction($connection);
//close client connection
$connection->close();
} else {
resp($connection)->send('system.ping');
$this->lastUnansweredPings[$connection->getConnectionId()] = true;
}
}
$loop++;
});
}
}
/**
* Display message to console if certain condition returns true
* @param mixed $data
* @param false $condition
* @return $this
*/
public function write($data, $condition = false)
{
if ($condition == 'true') {
console(true)->write($data);
}
return $this;
}
protected function closeAction(ConnectionInterface $connection)
{
//remove client from list of connected clients
$this->connections->detach($connection);
event()->emit('chat.public.removeUser', [$connection]);
}
public function onOpen(ConnectionInterface $connection)
{
// Store the new connection to send messages to later
$this->connections->attach($connection);
$this->currClient = $connection;
//Let client know within which time interval we'll send ping message
setTimeout(0.1, function () use ($connection) {
resp($connection)->send('system.ping.interval', $_ENV['CLIENT_PING_INTERVAL']);
});
$this->write("\n" . date('H:i:s'));
$this->write(color("\n -> Connection({$connection->getConnectionId()}) Established.\n")->fg('light_yellow'));
}
public function onMessage(ConnectionInterface $connection, Payload $payload)
{
if ($_ENV['SHOW_SOCKET_INCOMING_MESSAGES'] == 'true') {
//We don't want to display unnecessary logs
if (
$payload->command != 'system.ping'
&& $payload->command != 'system.pong'
&& $payload->command != 'system.ping.interval'
) {
$this->write("\n" . date('H:i:s'), true);
$this->write(color(" -> Message Received({$connection->getConnectionId()}): {$payload->getOriginalPayload()}")->fg('light_blue'), true);
}
}
$request = new Request([
'colis' => $this->colis,
'clients' => $this->connections,
'client' => $connection,
'message' => $payload,
'payload' => $payload,
]);
/**
* Check if sent command matches any provided listeners
* If its available the command class will be executed
*/
try {
Dispatcher::dispatch($request);
} catch (Exception $e) {
handleApplicationException($e);
}
}
public function onClose(ConnectionInterface $connection)
{
$this->closeAction($connection);
$this->write("\n\n" . date('H:i:s'));
$this->write(color("\n -> Connection({$connection->getConnectionId()}): disconnected.\n")->fg('light_red'));
}
public function onError(ConnectionInterface $connection, Throwable $exception)
{
$this->write("\n\n" . date('H:i:s'));
$this->write("\n[*] Error: {$exception->getMessage()} \n=> {$exception->getFile()} \n@ Line {$exception->getLine()}\n");
$connection->close();
}
}