SocketServer.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Helpers\Jwt;
  4. use App\Models\DepositModel;
  5. use App\Models\MessageModel;
  6. use App\Services\Api\DepositService;
  7. use App\Services\Api\MemberService;
  8. use App\Services\Api\OrderService;
  9. use App\Services\Common\MessageService;
  10. use App\Services\ConfigService;
  11. use App\Services\RedisService;
  12. use Illuminate\Console\Command;
  13. class SocketServer extends Command
  14. {
  15. public $ws;
  16. /**
  17. * The name and signature of the console command.
  18. *
  19. * @var string
  20. */
  21. protected $signature = 'swoole:chat {op?}';
  22. /**
  23. * The console command description.
  24. *
  25. * @var string
  26. */
  27. protected $description = 'Chat server run';
  28. protected $logger = null;
  29. /**
  30. * Create a new command instance.
  31. *
  32. * @return void
  33. */
  34. public function __construct()
  35. {
  36. parent::__construct();
  37. }
  38. /**
  39. * Execute the console command.
  40. *
  41. * @return mixed
  42. */
  43. public function handle()
  44. {
  45. $op = $this->argument('op');
  46. $op = $op ? $op : 'start';
  47. if ($op == 'start') {
  48. echo "swoole chat service start ...\n";
  49. $this->start();
  50. } else if ($op == 'stop') {
  51. echo "swoole chat service stop ...\n";
  52. $this->stop();
  53. }
  54. }
  55. /**
  56. * 运行
  57. */
  58. public function start()
  59. {
  60. try {
  61. //创建websocket服务器对象,监听0.0.0.0:7104端口
  62. $this->ws = new \Swoole\WebSocket\Server("0.0.0.0", env('SOCKET_PORT', '8660'));
  63. //监听WebSocket连接打开事件
  64. $this->ws->on('open', [$this, 'open']);
  65. //监听WebSocket消息事件
  66. $this->ws->on('message', [$this, 'message']);
  67. //监听WebSocket主动推送消息事件
  68. $this->ws->on('request', [$this, 'request']);
  69. //监听WebSocket连接关闭事件
  70. $this->ws->on('close', [$this, 'close']);
  71. $this->ws->start();
  72. } catch (\Exception $exception) {
  73. $date = date('Y-m-d H:i:s');
  74. RedisService::set("caches:sockets:error", $exception->getMessage(), 600);
  75. $this->info("【{$date}】Socket:运行异常=》" . $exception->getMessage());
  76. }
  77. }
  78. /**
  79. * 建立连接
  80. * @param $ws
  81. * @param $request
  82. */
  83. public function open($ws, $request)
  84. {
  85. $date = date('Y-m-d H:i:s');
  86. $logFile = '/storage/logs/swoole-task-'.date('Y-m-d', time() - 86400).'.log';
  87. if(file_exists(base_path().$logFile)){
  88. unlink(base_path().$logFile);
  89. }
  90. $fdData = RedisService::get("chats:bind:chat_1");
  91. $customFd = $fdData && isset($fdData['fd'])? $fdData['fd'] : 0;
  92. $checkFd = RedisService::get("chats:frames:" . $customFd);
  93. RedisService::clear('chats:checkCustom:from_'.$request->fd);
  94. $this->ws->push($request->fd, json_encode(['success' => 'true', 'op' => 'conn', 'message' => '连接成功','custom_fd'=>$checkFd && $customFd? $customFd:0, 'fd' => $request->fd], 256));
  95. $this->info("【{$date}】Socket:客户端【{$request->fd}】连接成功");
  96. }
  97. /**
  98. * 接收消息
  99. * @param $ws
  100. * @param $frame
  101. */
  102. public function message($ws, $frame)
  103. {
  104. $date = date('Y-m-d H:i:s');
  105. RedisService::set("chats:frames:" . $frame->fd, json_decode($frame->data, true), 86400);
  106. $fdData = RedisService::get("chats:bind:chat_1");
  107. $customFd = $fdData && isset($fdData['fd'])? $fdData['fd'] : 0;
  108. if ($frame->data == 'ping') {
  109. $this->ws->push($frame->fd, 'pong');
  110. if($customFd != $frame->fd){
  111. $this->sendMsg($frame->fd, ['success' => true,'op'=>'custom', 'message' => $customFd?'客服上线':'客服离线', 'scene'=>'check', 'data' => ['online'=>$customFd,'to_fd'=>$customFd], 't' => time()]);
  112. }
  113. // 推送客服保证金信息
  114. if($customFd == $frame->fd){
  115. $messages = MessageService::make()->getUnreadList(0);
  116. $count = isset($messages['count'])? $messages['count'] : 0;
  117. if($count>0){
  118. $this->sendMsg($frame->fd, ['success' => true,'op'=>'notice', 'message' => '消息通知', 'scene'=>'deposit', 'data' => $messages, 't' => time()]);
  119. }
  120. }
  121. $this->info("【{$date}】Socket:客户端【{$frame->fd}】心跳包",false);
  122. return false;
  123. }
  124. // 推送客服保证金信息
  125. else if($customFd && RedisService::get("chats:frames:" . $customFd)){
  126. $messages = MessageService::make()->getUnreadList(0);
  127. $count = isset($messages['count'])? $messages['count'] : 0;
  128. if($count>0){
  129. $this->sendMsg($customFd, ['success' => true,'op'=>'notice', 'message' => '消息通知', 'scene'=>'deposit', 'data' => $messages, 't' => time()]);
  130. }
  131. }
  132. // 消息处理
  133. $frameId = $frame->fd;
  134. $data = $frame->data ? json_decode($frame->data, true) : [];
  135. $fromUid = isset($data['from_uid']) ? intval($data['from_uid']) : 0;
  136. $isCustom = isset($data['is_custom']) ? intval($data['is_custom']) : 0;
  137. $token = isset($data['token']) ? $data['token'] : '';
  138. $op = isset($data['op']) ? $data['op'] : '';
  139. $scene = isset($data['scene']) && $data['scene'] ? $data['scene'] : 'chat';
  140. $jwt = new Jwt('jwt_jd_app');
  141. $userId = $jwt->verifyToken($token);
  142. if (!$isCustom && $userId != $fromUid) {
  143. $this->info("【{$scene} {$date}】Socket:请先登录再连接【{$frameId}-{$fromUid}】");
  144. $this->sendMsg($frameId, ['success' => false, 'message' => '请先登录', 'scene'=>$scene, 'data' => $data, 't' => time()]);
  145. return false;
  146. }
  147. // 签名验证
  148. $system = isset($data['system']) ? $data['system'] : [];
  149. $uuid = isset($system['uuid'])? $system['uuid'] : 0;
  150. $ctime = isset($system['ct'])? $system['ct'] : 0;
  151. $message = isset($data['message']) ? trim($data['message']) : '';
  152. $sign = isset($data['sign']) ? trim($data['sign']) : '';
  153. $checkSign = getSign($op.'&'.$message.'&'.$fromUid.'&'.$uuid.'&'.$ctime);
  154. if($checkSign != $sign){
  155. $this->info("【{$scene} {$date}】Socket:签名失败【{$frameId}-{$fromUid}】");
  156. $this->sendMsg($frameId, ['success' => false, 'message' => '请求签名失败', 'scene'=>$scene,'sign'=>$checkSign, 'data' => $data, 't' => time()]);
  157. return false;
  158. }
  159. $toUid = isset($data['to_uid']) ? intval($data['to_uid']) : 0;
  160. $apiUrl = env('APP_URL','');
  161. $chatKey = isset($data['chat_key']) ? trim($data['chat_key']) : '';
  162. $chatKey = $chatKey ? $chatKey : getChatKey($fromUid, $toUid);
  163. try {
  164. // 推送Fd处理
  165. if ($fromUid && $frameId) {
  166. RedisService::set("chats:bind:{$scene}_{$fromUid}", ['fd' => $frameId,'scene'=>$scene, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 3600);
  167. }
  168. switch ($op) {
  169. case 'chat': // 图文聊天
  170. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  171. // 发送参数验证
  172. if ($fromUid <= 0 || empty($message)) {
  173. $this->info("【{$scene} {$date}】Chat:参数错误,from@{$fromUid}-to@{$toUid}。");
  174. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  175. return false;
  176. }
  177. // 用户私聊
  178. $fromInfo = [];
  179. if($fromUid>1){
  180. $fromInfo = MemberService::make()->getInfo(['id'=> $fromUid,'status'=>1],[],false);
  181. if(empty($fromInfo)){
  182. $this->info("【{$scene} {$date}】Chat:发送用户不存在,from@{$fromUid}-to@{$toUid}。");
  183. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '您的账号不可用或已冻结,请联系客服']);
  184. return false;
  185. }
  186. }
  187. $toInfo = [];
  188. if($toUid>1){
  189. $toInfo = MemberService::make()->getInfo(['id'=> $toUid,'status'=>1],[],false);
  190. if(empty($toInfo)){
  191. $this->info("【{$scene} {$date}】Chat:接收用户不存在,from@{$fromUid}-to@{$toUid}。");
  192. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '对方账号不可用或无法接收消息']);
  193. return false;
  194. }
  195. }
  196. $fromUserName = isset($fromInfo['nickname'])? $fromInfo['nickname'] : ($fromUid>1? '用户'.$fromUid:'客服');
  197. $fromAvatar = isset($fromInfo['avatar']) && $fromInfo['avatar']? $fromInfo['avatar'] : get_image_url($fromUid>1?'/images/member/logo.png':'/images/member/custom.png');
  198. $toUserName = isset($toInfo['nickname'])? $toInfo['nickname'] : ($toUid>1? '用户'.$toUid:'客服');
  199. $toAvatar = isset($toInfo['avatar']) && $toInfo['avatar']? $toInfo['avatar'] : get_image_url($toUid>1?'/images/member/logo.png':'/images/member/custom.png');
  200. $msgData = [
  201. 'from_uid' => $fromUid,
  202. 'to_uid' => $toUid,
  203. 'type' => 1,
  204. 'msg_type' => $msgType,
  205. 'title' => '聊天消息',
  206. 'description' => $msgType == 2 ? '[图片]' : mb_substr($message, 0, 20),
  207. 'content' => $msgType==2? get_image_path($message) : $message,
  208. 'chat_key' => $chatKey,
  209. 'create_time' => time(),
  210. 'update_time' => time(),
  211. 'is_read' => 2,
  212. 'status' => 1
  213. ];
  214. if (!$id = MessageModel::insertGetId($msgData)) {
  215. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  216. $this->sendMsg($frameId, $data);
  217. return false;
  218. }
  219. // 推送消息给对方
  220. $msgData['from_user_name'] = $fromUserName;
  221. $msgData['from_user_avatar'] = get_image_url($fromAvatar, $apiUrl);
  222. $msgData['to_user_name'] = $toUserName;
  223. $msgData['to_user_avatar'] = get_image_url($toAvatar, $apiUrl);
  224. $msgData['time_text'] = dateFormat($msgData['create_time']);
  225. if($msgData['msg_type'] == 1 || $msgData['msg_type'] == 3){
  226. $msgData['content'] = format_message($msgData['content']);
  227. }else if($msgData['msg_type'] == 2){
  228. $msgData['content'] = $msgData['content']? get_image_url($msgData['content'],$apiUrl) : '';
  229. }else if($msgData['msg_type'] == 4){
  230. $msgData['content'] = $msgData['content']? json_decode($msgData['content'], true) : [];
  231. }
  232. // 接收方缓存
  233. RedisService::clear("caches:messages:unread_count_{$toUid}");
  234. // 返回自身消息
  235. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene,'custom_fd'=>$customFd, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  236. // 推送给对方消息
  237. $pushCustom = ConfigService::make()->getConfigByCode('push_custom_message',1);
  238. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  239. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  240. if ($toBindData && $toFd) {
  241. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene,'custom_fd'=>$customFd, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  242. $this->info("【{$date}】Chat:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  243. }
  244. // 如果开启离线推送,或一直推送,根据关键词推送客服消息
  245. if((($pushCustom == 1 && !$toFd)||($pushCustom==2) && ($msgType == 1) )&& $fromUid >1){
  246. // 搜索内容
  247. $replyContent = ConfigService::make()->getContentByKw($message);
  248. $sendData = $msgData = [
  249. 'from_uid' => 1,
  250. 'to_uid' => $fromUid,
  251. 'type' => 1,
  252. 'msg_type' => 3,
  253. 'title' => '客服消息',
  254. 'description' => mb_substr($message, 0, 20),
  255. 'content' => $replyContent,
  256. 'chat_key' => $chatKey,
  257. 'create_time' => time(),
  258. 'update_time' => time(),
  259. 'is_read' => 1,
  260. 'status' => 1
  261. ];
  262. $sendData['from_user_name'] = $toUserName;
  263. $sendData['from_user_avatar'] = $toAvatar;
  264. $sendData['to_user_name'] = $fromUserName;
  265. $sendData['to_user_avatar'] = $fromAvatar;
  266. $sendData['content'] = format_message($replyContent);
  267. $sendData['time_text'] = dateFormat($msgData['create_time']);
  268. if($replyContent){
  269. if (MessageModel::insertGetId($msgData)) {
  270. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $sendData, 'message' => '回复成功:' . $frameId]);
  271. }
  272. }else{
  273. $replyContent = ConfigService::make()->getConfigByCode('custom_offline_reply','');
  274. if($replyContent){
  275. $sendData['content'] = format_message($replyContent);
  276. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $sendData, 'message' => '回复成功:' . $frameId]);
  277. }
  278. }
  279. }
  280. break;
  281. case 'refund_apply': // 保证金退款申请消息通知
  282. $orderId = isset($data['order_id'])? $data['order_id'] : 0;
  283. // 发送参数验证
  284. if ($fromUid <= 0 || empty($message) || empty($orderId)) {
  285. $this->info("【{$scene} {$date}】Message:参数错误,from@{$fromUid}-to@{$toUid}。");
  286. $this->sendMsg($frameId, ['success' => false,'op'=>'notice','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  287. return false;
  288. }
  289. // 订单信息
  290. $orderInfo = DepositService::make()->getInfo($orderId);
  291. $orderNo = isset($orderInfo['refund_no'])? $orderInfo['refund_no'] : '';
  292. $orderMoney = isset($orderInfo['refund_money'])? $orderInfo['refund_money'] : 0;
  293. if(empty($orderInfo) || $orderMoney<=0){
  294. $this->info("【{$scene} {$date}】Message:订单信息不存在,from@{$fromUid}-to@{$toUid}-{$orderId}。");
  295. $this->sendMsg($frameId, ['success' => false,'op'=>'notice','scene'=>$scene,'data'=>$data, 'message' => '订单信息不存在']);
  296. return false;
  297. }
  298. $msgData = [
  299. 'from_uid' => $fromUid,
  300. 'to_uid' => $toUid,
  301. 'type' => 4,
  302. 'msg_type' => 4,
  303. 'title' => '保证金退款申请消息',
  304. 'description' => $message,
  305. 'order_no' => $orderNo,
  306. 'content' => json_encode([
  307. 'title'=> $message.'<span class="ele-text-primary">查看订单</span>',
  308. 'order_no'=> $orderNo,
  309. 'money'=> $orderMoney,
  310. 'date'=> date('Y-m-d H:i:s'),
  311. 'user_id'=> $fromUid,
  312. 'type'=> 'deposit',
  313. 'remark'=> '退保申请',
  314. ],256),
  315. 'chat_key' => $chatKey,
  316. 'create_time' => time(),
  317. 'update_time' => time(),
  318. 'is_read' => 2,
  319. 'status' => 1
  320. ];
  321. if (!$id = MessageModel::insertGetId($msgData)) {
  322. $data = ['success' => false,'op'=>'notice','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  323. $this->sendMsg($frameId, $data);
  324. return false;
  325. }
  326. // 推送消息给对方
  327. $msgData['time_text'] = dateFormat($msgData['create_time']);
  328. $msgData['content'] = $msgData['content']? json_decode($msgData['content'], true) : [];
  329. // 返回自身消息
  330. $this->sendMsg($frameId, ['success' => true, 'op' => 'notice', 'scene'=> $scene,'custom_fd'=>$customFd, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  331. // 推送给对方消息
  332. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  333. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  334. if ($toBindData && $toFd) {
  335. $this->sendMsg($toFd, ['success' => true, 'op' => 'notice' ,'scene'=> $scene,'custom_fd'=>$customFd, 'data' => ['count'=>1,'list'=>[$msgData]], 'message' => '推送消息成功:' . $toFd]);
  336. $this->info("【{$date}】Message:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  337. }
  338. break;
  339. case 'notice': // 其他消息通知
  340. $type = isset($data['type']) ? $data['type'] : 5;
  341. $order = isset($data['order']) ? $data['order'] : [];
  342. // 发送参数验证
  343. if ($fromUid <= 0 || empty($message) || empty($order)) {
  344. $this->info("【{$scene} {$date}】Message:参数错误,from@{$fromUid}-to@{$toUid}。");
  345. $this->sendMsg($frameId, ['success' => false,'op'=>'notice','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  346. return false;
  347. }
  348. $msgData = [
  349. 'from_uid' => $fromUid,
  350. 'to_uid' => $toUid,
  351. 'type' => $type,
  352. 'msg_type' => 4,
  353. 'title' => $message,
  354. 'order_no' => isset($order['order_no'])?$order['order_no'] : '',
  355. 'description' => isset($order['title'])? $order['title'] : '有新的订单消息',
  356. 'content' => json_encode($order,256),
  357. 'chat_key' => $chatKey,
  358. 'create_time' => time(),
  359. 'update_time' => time(),
  360. 'is_read' => 2,
  361. 'status' => 1
  362. ];
  363. if (!$id = MessageModel::insertGetId($msgData)) {
  364. $data = ['success' => false,'op'=>'notice','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  365. $this->sendMsg($frameId, $data);
  366. return false;
  367. }
  368. // 推送消息给对方
  369. $msgData['time_text'] = dateFormat($msgData['create_time']);
  370. $msgData['content'] = $msgData['content']? json_decode($msgData['content'], true) : [];
  371. // 返回自身消息
  372. $this->sendMsg($frameId, ['success' => true, 'op' => 'notice', 'scene'=> $scene,'custom_fd'=>$customFd, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  373. // 推送给对方消息
  374. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  375. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  376. echo $toFd;
  377. if ($toBindData && $toFd) {
  378. $this->sendMsg($toFd, ['success' => true, 'op' => 'notice' ,'scene'=> $scene,'custom_fd'=>$customFd, 'data' => ['count'=>1,'list'=>[$msgData]], 'message' => '推送消息成功:' . $toFd]);
  379. $this->info("【{$date}】Message:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  380. }
  381. break;
  382. case 'login': // 登录
  383. if($toUid<=0){
  384. $toUid = 1;
  385. $data['to_uid'] = $toUid;
  386. $data['is_custom'] = true;
  387. $data['to_user_name'] = '客服';
  388. }
  389. // 未读消息
  390. $unreadCount = 0;
  391. if($fromUid==1){
  392. $unreadCount = intval(\App\Services\Api\MessageService::make()->getUnreadCount(1));
  393. }
  394. $fdData = RedisService::get("chats:bind:chat_".$toUid);
  395. $toFd = $fdData && isset($fdData['fd'])? $fdData['fd'] : 0;
  396. $checkFd = RedisService::get("chats:frames:" . $toFd);
  397. $online = $checkFd && $toFd? 1 : 0;
  398. $data['to_fd'] = $online? $toFd : 0;
  399. $data['chat_key'] = getChatKey($fromUid,$toUid);
  400. $this->info("【{$scene} {$date}】Socket:登录成功【{$frameId}-{$fromUid}-{$op}】。");
  401. $this->sendMsg($frameId, ['success' => true,'op'=> $op, 'scene'=>$scene,'custom_fd'=>$customFd,'unread'=>$unreadCount, 'message' => '登录成功', 'data' => $data, 't' => time()]);
  402. break;
  403. default:
  404. $this->sendMsg($frameId, ['success' => false, 'message' => 'ok', 'scene'=>$scene,'custom_fd'=>$customFd, 'data' => $data, 't' => time()]);
  405. break;
  406. }
  407. $this->info("【{$scene} {$date}】Chat:客户端【{$frameId}】消息处理成功");
  408. } catch (\Exception $exception) {
  409. RedisService::set("caches:sockets:error_{$frameId}", ['error' => $exception->getMessage(),'trace'=>$exception->getTrace(), 'date' => $date], 7200);
  410. $this->info("【{$scene} {$date}】Chat:客户端【{$frameId}】消息处理错误 " . $exception->getMessage());
  411. }
  412. }
  413. /**
  414. * 签名验证
  415. * @param $data
  416. * @return bool
  417. */
  418. public function checkSign($data)
  419. {
  420. $checkSign = isset($data['sign']) ? $data['sign'] : '';
  421. $sign = getSign($data);
  422. if ($sign != $checkSign) {
  423. return false;
  424. }
  425. return true;
  426. }
  427. /**
  428. * 推送消息
  429. * @param $fd
  430. * @param $op
  431. * @param $data
  432. */
  433. public function sendMsg($fd, $data)
  434. {
  435. $date = date('Y-m-d H:i:s');
  436. try {
  437. if (!RedisService::exists("chats:frames:" . $fd)) {
  438. $this->info("【{$date}】Chat:客户端【{$fd}】推送用户已经掉线 ");
  439. return false;
  440. }
  441. $this->ws->push($fd, json_encode($data, 256));
  442. } catch (\Exception $exception) {
  443. $this->info("【{$date}】Chat:客户端【{$fd}】消息处理错误 " . $exception->getMessage());
  444. }
  445. }
  446. /**
  447. * 接收请求
  448. * @param $request
  449. * @param $response
  450. */
  451. public function request($request, $response)
  452. {
  453. }
  454. /**
  455. * 关闭连接
  456. * @param $ws
  457. * @param $fd
  458. */
  459. public function close($ws, $fd = '')
  460. {
  461. $date = date('Y-m-d H:i:s');
  462. RedisService::clear("chats:frames:" . $fd);
  463. $this->info("【{$date}】Chat:客户端【{$fd}】连接关闭");
  464. RedisService::clear('chats:checkCustom:from_'.$fd);
  465. $this->ws->close($fd);
  466. // 清理历史消息
  467. if(!RedisService::get("caches:messages:clear")){
  468. $expireTime = ConfigService::make()->getConfigByCode('chat_log_expire',30);
  469. $expireTime = $expireTime>0 && $expireTime <= 365? $expireTime : 30;
  470. $expireTime = $expireTime * 24 * 3600;
  471. MessageModel::where('create_time','<', time() - $expireTime)->delete();
  472. }
  473. }
  474. /**
  475. * 停止运行
  476. */
  477. public function stop()
  478. {
  479. // 直接杀
  480. $stoSh = base_path().'/crontab/socketStop.sh';
  481. if(file_exists($stoSh) && function_exists('exec')){
  482. exec("{$stoSh}");
  483. }
  484. echo "$stoSh\n";
  485. echo "chat stop success...\n";
  486. if ($this->ws) {
  487. $date = date('Y-m-d H:i:s');
  488. $this->info("【{$date}】Chat:停止运行服务");
  489. $this->ws->close();
  490. }
  491. }
  492. /**
  493. * 消息
  494. * @param string $data
  495. */
  496. public function info($data,$verbosity=true)
  497. {
  498. \logger()->channel('chat')->info($data);
  499. if(env('SWOOLE_LOG', true) && $verbosity){
  500. parent::info($data);
  501. }
  502. }
  503. }