<?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");
|
}
|
}
|