forked from alucn/laychat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Events.php
106 lines (101 loc) · 3.75 KB
/
Events.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
101
102
103
104
105
106
<?php
use \GatewayWorker\Lib\Gateway;
/**
* 主逻辑
* 主要是处理 onConnect onMessage onClose 三个方法
* onConnect 和 onClose 如果不需要可以不用实现并删除
*/
class Events
{
/**
* 当客户端发来消息时触发
* @param int $client_id 连接id
* @param mixed $message 具体消息
*/
public static function onMessage($client_id, $data) {
$message = json_decode($data, true);
$message_type = $message['type'];
switch($message_type) {
case 'init':
// uid
$uid = $message['id'];
// 设置session
$_SESSION = array(
'username' => $message['username'],
'avatar' => $message['avatar'],
'id' => $uid,
'sign' => $message['sign']
);
// 将当前链接与uid绑定
Gateway::bindUid($client_id, $uid);
// 通知当前客户端初始化
$init_message = array(
'message_type' => 'init',
'id' => $uid,
);
Gateway::sendToClient($client_id, json_encode($init_message));
// 通知所有客户端添加一个好友
$reg_message = array('message_type'=>'addList', 'data'=>array(
'type' => 'friend',
'username' => $message['username'],
'avatar' => $message['avatar'],
'id' => $uid,
'sign' => $message['sign'],
'groupid' => 1
));
Gateway::sendToAll(json_encode($reg_message), null, $client_id);
// 让当前客户端加入群组101
Gateway::joinGroup($client_id, 101);
return;
case 'chatMessage':
// 聊天消息
$type = $message['data']['to']['type'];
$to_id = $message['data']['to']['id'];
$uid = $_SESSION['id'];
$chat_message = array(
'message_type' => 'chatMessage',
'data' => array(
'username' => $_SESSION['username'],
'avatar' => $_SESSION['avatar'],
'id' => $type === 'friend' ? $uid : $to_id,
'type' => $type,
'content' => htmlspecialchars($message['data']['mine']['content']),
'timestamp'=> time()*1000,
)
);
switch ($type) {
// 私聊
case 'friend':
return Gateway::sendToUid($to_id, json_encode($chat_message));
// 群聊
case 'group':
return Gateway::sendToGroup($to_id, json_encode($chat_message), $client_id);
}
return;
case 'hide':
case 'online':
$status_message = array(
'message_type' => $message_type,
'id' => $_SESSION['id'],
);
$_SESSION['online'] = $message_type;
Gateway::sendToAll(json_encode($status_message));
return;
case 'ping':
return;
default:
echo "unknown message $data";
}
}
/**
* 当用户断开连接时触发
* @param int $client_id 连接id
*/
public static function onClose($client_id) {
$logout_message = array(
'message_type' => 'logout',
'id' => $_SESSION['id']
);
Gateway::sendToAll(json_encode($logout_message));
}
}