|
| 1 | +<?php |
| 2 | +use \GatewayWorker\Lib\Gateway; |
| 3 | + |
| 4 | +/** |
| 5 | + * 主逻辑 |
| 6 | + * 主要是处理 onConnect onMessage onClose 三个方法 |
| 7 | + * onConnect 和 onClose 如果不需要可以不用实现并删除 |
| 8 | + */ |
| 9 | +class Events |
| 10 | +{ |
| 11 | + /** |
| 12 | + * 当客户端发来消息时触发 |
| 13 | + * @param int $client_id 连接id |
| 14 | + * @param mixed $message 具体消息 |
| 15 | + */ |
| 16 | + public static function onMessage($client_id, $data) { |
| 17 | + $message = json_decode($data, true); |
| 18 | + switch($message['type']) { |
| 19 | + case 'init': |
| 20 | + // 设置session |
| 21 | + $_SESSION = array( |
| 22 | + 'username' => $message['username'], |
| 23 | + 'avatar' => $message['avatar'], |
| 24 | + 'id' => $client_id, |
| 25 | + 'sign' => $message['sign'] |
| 26 | + ); |
| 27 | + // 获得了client_id,通知当前客户端初始化 |
| 28 | + $init_message = array( |
| 29 | + 'message_type' => 'init', |
| 30 | + 'client_id' => $client_id, |
| 31 | + ); |
| 32 | + Gateway::sendToClient($client_id, json_encode($init_message)); |
| 33 | + |
| 34 | + // 通知所有客户端添加一个好友 |
| 35 | + $reg_message = array('message_type'=>'addList', 'data'=>array( |
| 36 | + 'type' => 'friend', |
| 37 | + 'username' => $message['username'], |
| 38 | + 'avatar' => $message['avatar'], |
| 39 | + 'id' => $client_id, |
| 40 | + 'sign' => $message['sign'], |
| 41 | + 'groupid' => 1 |
| 42 | + )); |
| 43 | + Gateway::sendToAll(json_encode($reg_message), null, $client_id); |
| 44 | + |
| 45 | + // 让当前客户端加入群组101 |
| 46 | + Gateway::joinGroup($client_id, 101); |
| 47 | + return; |
| 48 | + case 'chatMessage': |
| 49 | + // 聊天消息 |
| 50 | + $type = $message['data']['to']['type']; |
| 51 | + $to_id = $message['data']['to']['id']; |
| 52 | + $chat_message = array( |
| 53 | + 'message_type' => 'chatMessage', |
| 54 | + 'data' => array( |
| 55 | + 'username' => $_SESSION['username'], |
| 56 | + 'avatar' => $_SESSION['avatar'], |
| 57 | + 'id' => $type === 'friend' ? $client_id : $to_id, |
| 58 | + 'type' => $type, |
| 59 | + 'content' => $message['data']['mine']['content'], |
| 60 | + 'timestamp'=> time()*1000, |
| 61 | + ) |
| 62 | + ); |
| 63 | + if($type === 'friend'){ |
| 64 | + // 私聊 |
| 65 | + Gateway::sendToClient($to_id, json_encode($chat_message)); |
| 66 | + } else { |
| 67 | + // 群聊 |
| 68 | + Gateway::sendToGroup($to_id, json_encode($chat_message), $client_id); |
| 69 | + } |
| 70 | + return; |
| 71 | + default: |
| 72 | + echo "unknown message $data"; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * 当用户断开连接时触发 |
| 78 | + * @param int $client_id 连接id |
| 79 | + */ |
| 80 | + public static function onClose($client_id) { |
| 81 | + $logout_message = array( |
| 82 | + 'message_type' => 'logout', |
| 83 | + 'id' => $client_id |
| 84 | + ); |
| 85 | + Gateway::sendToAll(json_encode($logout_message)); |
| 86 | + } |
| 87 | +} |
0 commit comments