liyaozhi
2025-11-27 d729c91f610c8902fcec2444df6cac7b1c2e1002
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
<?php
/**
 * 用于名片聊天的业务逻辑
 * 处理 onConnect onMessage onClose 三个方法
 */
 
namespace app\gateway;
 
use \GatewayWorker\Lib\Gateway;
use app\api\model\plus\business\chat\Chat as BusinessChatModel;
use Workerman\Lib\Timer;
use Workerman\Worker;
use think\worker\Application;
 
/**
 * 名片聊天主逻辑
 */
class BusinessEvents
{
    /**
     * onWorkerStart 事件回调
     * 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
     *
     * @access public
     * @param \Workerman\Worker $businessWorker
     * @return void
     */
    public static function onWorkerStart(Worker $businessWorker)
    {
        $app = new Application;
        $app->initialize();
    }
 
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据
        $data['client_id'] = $client_id;
        $data['type'] = 'init';
        Gateway::sendToClient($client_id, json_encode($data));
    }
 
    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        $data = json_decode($message, 1);
        $to = 'user_' . $data['to_user_id'];
        $from_id = 'user_' . $data['user_id'];
        
        if ($data['type'] !== 'ping' && $data['type'] !== 'close') {//正常发送消息
            if (Gateway::isUidOnline($to)) {
                $data['time'] = date('Y-m-d H:i:s');
                Gateway::sendToUid($to, json_encode($data));
            }
            
            // 保存消息到数据库
            $Chat = new BusinessChatModel;
            $Chat->addBusinessMessage($data, ['user_id' => $data['user_id']]);
        } else if ($data['type'] == 'ping') {
            //心跳
            $data['Online'] = $to && Gateway::isUidOnline($to) ? 'on' : 'off';
            Gateway::sendToUid($from_id, json_encode($data));
        } else if ($data['type'] == 'close') {
            //断开链接
            Gateway::unbindUid($client_id, $from_id);
        }
    }
 
    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // 向所有人发送
        //GateWay::sendToAll("$client_id logout\r\n");
    }
}