Files
2025-11-29 10:40:00 +08:00

78 lines
2.4 KiB
PHP

<?php
require_once COMMPATH . 'libraries/JWT.php';
require_once COMMPATH . 'libraries/websocket/WsResponse.php';
use WebSocket\Client;
use \Firebase\JWT\JWT;
/**
* websocket 推送客户端
*/
class WsClient
{
private $client;
private $ci;
private $jwt_key_system;
public function __construct($params = [])
{
$this->ci = &get_instance();
$this->ci->load->library('myResponse');
$this->ci->config->load('wss');
$url = $this->ci->config->item('url');
$this->jwt_key_system = $this->ci->config->item('jwt_key_system');
$sendPlatform = $params['platform']; //推送消息平台
if (!$sendPlatform) {
throw new Exception('请指定推送平台');
}
$uid = $params['uid'];
if (!$uid) {
throw new Exception('请指定推送用户');
}
$token = $this->createToken($uid);
if (!$url) {
throw new Exception('请配置websocket服务地址');
}
$url = $url . '?platform=' . $sendPlatform . '&token=' . $token;
$this->client = new Client($url);
}
/**
* 发送websocket消息
* @param $requestId
* @param $targetPlatform 接收数据平台
* @param $targetUid 目标用户id
* @param $data 推送数据
* @return MyResponse
*/
public function sendMessage($requestId, $targetPlatform, $targetUid, $data)
{
try {
if (!$targetPlatform || !$targetUid || !$data) {
throw new Exception('参数错误');
}
$sendData = [
'requestId' => $requestId,
'type' => WsResponse::MST_TYPE_MSG,
'targetPlatform' => $targetPlatform,
'targetUid' => $targetUid,
'data' => $data
];
$this->client->send(json_encode($sendData, JSON_UNESCAPED_UNICODE));
$req = $this->client->receive();
$this->client->close();
$reqData = json_decode($req, true);
if (!isset($reqData['code']) || $reqData['code']) {
throw new Exception($reqData['msg'] ?: '发送失败');
}
return new MyResponse(EXIT_SUCCESS, '发送成功', $reqData);
} catch (Exception $e) {
return new MyResponse(EXIT_ERROR, $e->getMessage());
}
}
public function createToken($uid)
{
return JWT::encode($uid, $this->jwt_key_system);
}
}