-
Notifications
You must be signed in to change notification settings - Fork 2
/
event_worker.php
96 lines (86 loc) · 2.48 KB
/
event_worker.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
<?php
declare(strict_types=1);
use Swoole\Timer;
use Xielei\Swoole\Api;
use Xielei\Swoole\Helper\WorkerEvent as HelperWorkerEvent;
class WorkerEvent extends HelperWorkerEvent
{
public function onWorkerStart()
{
if ($this->worker->getServer()->worker_id == 0) {
$this->xtimer = Timer::tick(5000, function () {
Api::sendToAll(json_encode([
'event' => 'groupList',
'data' => $this->getGroupList(),
]));
});
}
}
public function onWorkerExit()
{
if (isset($this->xtimer)) {
Timer::clear($this->xtimer);
}
}
public function onConnect(string $client, array $session)
{
Api::sendToClient($client, json_encode([
'event' => 'connect',
'data' => $client,
]));
}
public function onReceive(string $client, array $session, string $data)
{
try {
if (substr($data, 0, 1) !== '{') {
return;
}
$data = json_decode($data, true);
$event = $data['event'];
$cmd = $data['cmd'];
$param = $data['param'];
switch ($cmd) {
case 'getGroupListInfo':
$res = $this->getGroupList();
break;
default:
$res = Api::$cmd(...$param);
break;
}
if ($event) {
if ($res instanceof Iterator) {
$res = iterator_to_array($res);
}
Api::sendToClient($client, json_encode([
'event' => $event,
'data' => $res,
]));
}
} catch (\Throwable $th) {
Api::sendToClient($client, json_encode([
'event' => 'error',
'data' => $th->getMessage(),
]));
}
}
public function onClose(string $client, array $session, array $bind)
{
Api::sendToAll(json_encode([
'event' => 'close',
'data' => [
'client' => $client,
'group_list' => $bind['group_list'],
],
]));
}
private function getGroupList(): array
{
$res = [
'大厅' => 0,
];
foreach (Api::getGroupList(true) as $group) {
$res[$group] = Api::getClientCountByGroup($group);
}
return $res;
}
}