-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathChatWorker.php
More file actions
215 lines (186 loc) · 8.06 KB
/
Copy pathChatWorker.php
File metadata and controls
215 lines (186 loc) · 8.06 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
<?php
// Подключаем библиотеку Workerman
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Lib\Timer;
use Workerman\Worker;
$connections = []; // сюда будем складывать все подключения
// Стартуем WebSocket-сервер на порту 27800
$worker = new Worker("websocket://0.0.0.0:27800");
$worker->onWorkerStart = function($worker) use (&$connections)
{
$interval = 5; // пингуем каждые 5 секунд
Timer::add($interval, function() use(&$connections) {
foreach ($connections as $c) {
// Если ответ не пришел 3 раза, то удаляем соединение из списка
// и оповещаем всех участников об "отвалившемся" пользователе
if ($c->pingWithoutResponseCount >= 3) {
unset($connections[$c->id]);
$messageData = [
'action' => 'ConnectionLost',
'userId' => $c->id,
'userName' => $c->userName,
'gender' => $c->gender,
'userColor' => $c->userColor
];
$message = json_encode($messageData);
$c->destroy(); // уничтожаем соединение
foreach ($connections as $c) {
$c->send($message);
}
}
else {
$c->send('{"action":"Ping"}');
$c->pingWithoutResponseCount++; // увеличиваем счетчик пингов
}
}
});
};
$worker->onConnect = function($connection) use(&$connections)
{
// Эта функция выполняется при подключении пользователя к WebSocket-серверу
$connection->onWebSocketConnect = function($connection) use (&$connections)
{
// Достаём имя пользователя, если оно было указано
if (isset($_GET['userName'])) {
$originalUserName = preg_replace('/[^a-zA-Zа-яА-ЯёЁ0-9\-\_ ]/u', '', trim($_GET['userName']));
}
else {
$originalUserName = 'Инкогнито';
}
// Половая принадлежность, если указана
// 0 - Неизвестный пол
// 1 - М
// 2 - Ж
if (isset($_GET['gender'])) {
$gender = (int) $_GET['gender'];
}
else {
$gender = 0;
}
if ($gender != 0 && $gender != 1 && $gender != 2)
$gender = 0;
// Цвет пользователя
if (isset($_GET['userColor'])) {
$userColor = $_GET['userColor'];
}
else {
$userColor = "#000000";
}
// Проверяем уникальность имени в чате
$userName = $originalUserName;
$num = 2;
do {
$duplicate = false;
foreach ($connections as $c) {
if ($c->userName == $userName) {
$userName = "$originalUserName ($num)";
$num++;
$duplicate = true;
break;
}
}
}
while($duplicate);
// Добавляем соединение в список
$connection->userName = $userName;
$connection->gender = $gender;
$connection->userColor = $userColor;
$connection->pingWithoutResponseCount = 0; // счетчик безответных пингов
$connections[$connection->id] = $connection;
// Собираем список всех пользователей
$users = [];
foreach ($connections as $c) {
$users[] = [
'userId' => $c->id,
'userName' => $c->userName,
'gender' => $c->gender,
'userColor' => $c->userColor
];
}
// Отправляем пользователю данные авторизации
$messageData = [
'action' => 'Authorized',
'userId' => $connection->id,
'userName' => $connection->userName,
'gender' => $connection->gender,
'userColor' => $connection->userColor,
'users' => $users
];
$connection->send(json_encode($messageData));
// Оповещаем всех пользователей о новом участнике в чате
$messageData = [
'action' => 'Connected',
'userId' => $connection->id,
'userName' => $connection->userName,
'gender' => $connection->gender,
'userColor' => $connection->userColor
];
$message = json_encode($messageData);
foreach ($connections as $c) {
$c->send($message);
}
};
};
$worker->onClose = function($connection) use(&$connections)
{
// Эта функция выполняется при закрытии соединения
if (!isset($connections[$connection->id])) {
return;
}
// Удаляем соединение из списка
unset($connections[$connection->id]);
// Оповещаем всех пользователей о выходе участника из чата
$messageData = [
'action' => 'Disconnected',
'userId' => $connection->id,
'userName' => $connection->userName,
'gender' => $connection->gender,
'userColor' => $connection->userColor
];
$message = json_encode($messageData);
foreach ($connections as $c) {
$c->send($message);
}
};
$worker->onMessage = function($connection, $message) use (&$connections)
{
$messageData = json_decode($message, true);
$toUserId = isset($messageData['toUserId']) ? (int) $messageData['toUserId'] : 0;
$action = isset($messageData['action']) ? $messageData['action'] : '';
if ($action == 'Pong') {
// При получении сообщения "Pong", обнуляем счетчик пингов
$connection->pingWithoutResponseCount = 0;
}
else {
// Дополняем сообщение данными об отправителе
$messageData['userId'] = $connection->id;
$messageData['userName'] = $connection->userName;
$messageData['gender'] = $connection->gender;
$messageData['userColor'] = $connection->userColor;
// Преобразуем специальные символы в HTML-сущности в тексте сообщения
$messageData['text'] = htmlspecialchars($messageData['text']);
// Заменяем текст заключенный в фигурные скобки на жирный
$messageData['text'] = preg_replace('/\{(.*)\}/u', '<b>\\1</b>', $messageData['text']);
if ($toUserId == 0) {
// Отправляем сообщение всем пользователям
$messageData['action'] = 'PublicMessage';
foreach ($connections as $c) {
$c->send(json_encode($messageData));
}
}
else {
$messageData['action'] = 'PrivateMessage';
if (isset($connections[$toUserId])) {
// Отправляем приватное сообщение указанному пользователю
$connections[$toUserId]->send(json_encode($messageData));
// и отправителю
$connections->send(json_encode($messageData));
}
else {
$messageData['text'] = 'Не удалось отправить сообщение выбранному пользователю';
$connection->send(json_encode($messageData));
}
}
}
};
Worker::runAll();