-
Notifications
You must be signed in to change notification settings - Fork 0
/
Websocket.php
100 lines (86 loc) · 2.22 KB
/
Websocket.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
<?php
declare(strict_types=1);
namespace process;
use app\service\LogService;
use app\validate\LogValidate;
use Workerman\Connection\TcpConnection;
class Websocket {
public function __construct(
protected LogService $logService
) {
}
/**
* 进程入口
*
* @return void
*
* @author Jarvis
* @date 2024-02-18 22:32
*/
public function onWorkerStart(): void {
}
public function onConnect(TcpConnection $connection): void {
}
public function onWebSocketConnect(TcpConnection $connection, $http_buffer): void {
}
public function onClose(TcpConnection $connection): void {
}
/**
* 接收消息
*
* @param string $data
* @return void
*
* @author Jarvis
* @date 2024-02-25 00:41
*/
public function onMessage(TcpConnection $connection, $data): void {
if ($data == 'ping') {
return;
}
$data = json_decode($data, true);
if (empty($data)) {
$this->sendError($connection, '参数不能为空');
return;
}
try {
validate(LogValidate::class)->scene('create')->check($data);
$this->logService->add($data);
$this->sendSuccess($connection);
} catch (\Throwable $th) {
$this->sendError($connection, $th->getMessage());
}
}
/**
* 发送错误消息
*
* @param array|string $data
* @return void
*
* @author Jarvis
* @date 2024-02-25 00:39
*/
private function sendError(TcpConnection $connection, string $message, $data = null): void {
$connection->send(json_encode([
'code' => 1,
'msg' => $message,
'data' => $data ?? new \stdClass,
]));
}
/**
* 发送成功消息
*
* @param array|string $data
* @return void
*
* @author Jarvis
* @date 2024-02-25 14:25
*/
private function sendSuccess(TcpConnection $connection, string $message = 'success', $data = null): void {
$connection->send(json_encode([
'code' => 0,
'msg' => $message,
'data' => $data ?? new \stdClass,
]));
}
}