SocketServer.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Helpers\Jwt;
  4. use App\Models\LiveChatModel;
  5. use App\Models\LiveModel;
  6. use App\Models\MemberModel;
  7. use App\Models\MessageModel;
  8. use App\Models\VideoCollectModel;
  9. use App\Services\Api\MemberService;
  10. use App\Services\RedisService;
  11. use Illuminate\Console\Command;
  12. use Monolog\Logger;
  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:socket {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 socket service start ...\n";
  49. $this->start();
  50. } else if ($op == 'stop') {
  51. echo "swoole socket 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', '6530'));
  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. $this->ws->push($request->fd, json_encode(['success' => 'true', 'op' => 'conn', 'message' => '连接成功', 'fd' => $request->fd], 256));
  91. $this->info("【{$date}】Socket:客户端【{$request->fd}】连接成功");
  92. }
  93. /**
  94. * 接收消息
  95. * @param $ws
  96. * @param $frame
  97. */
  98. public function message($ws, $frame)
  99. {
  100. $date = date('Y-m-d H:i:s');
  101. RedisService::set("chats:frames:" . $frame->fd, json_decode($frame->data, true), 86400);
  102. if ($frame->data == 'ping') {
  103. $this->ws->push($frame->fd, 'pong');
  104. $this->info("【{$date}】Socket:客户端【{$frame->fd}】心跳包",false);
  105. return false;
  106. }
  107. // 消息处理
  108. $frameId = $frame->fd;
  109. $data = $frame->data ? json_decode($frame->data, true) : [];
  110. $fromUid = isset($data['from_uid']) ? intval($data['from_uid']) : 0;
  111. $token = isset($data['token']) ? $data['token'] : '';
  112. $op = isset($data['op']) ? $data['op'] : '';
  113. $scene = isset($data['scene']) && $data['scene'] ? $data['scene'] : 'chat';
  114. $jwt = new Jwt();
  115. $userId = $jwt->verifyToken($token);
  116. if ($userId != $fromUid) {
  117. $this->info("【{$scene} {$date}】Socket:签名失败【{$frameId}-{$fromUid}】");
  118. return false;
  119. }
  120. $uuid = isset($data['uuid']) ? $data['uuid'] : uniqid();
  121. $toUid = isset($data['to_uid']) ? intval($data['to_uid']) : 0;
  122. $groupId = isset($data['group_id']) ? intval($data['group_id']) : 0;
  123. $apiUrl = env('APP_URL','');
  124. $chatKey = isset($data['chat_key']) ? trim($data['chat_key']) : '';
  125. $chatKey = $chatKey ? $chatKey : getChatKey($fromUid, $toUid);
  126. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  127. try {
  128. // 推送Fd处理
  129. if ($fromUid && $frameId) {
  130. if($groupId>0){
  131. $fds = RedisService::get("chats:bindFds:{$scene}_{$groupId}");
  132. $fds = $fds? $fds : [];
  133. $fds[$scene.'_'.$fromUid] = $frameId;
  134. RedisService::set("chats:bindFds:{$scene}_{$groupId}", $fds, 86400);
  135. RedisService::set("chats:bind:{$scene}_{$fromUid}", ['fd' => $frameId,'scene'=>$scene, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 86400);
  136. }else{
  137. $fds = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  138. $fds = $fds? $fds : [];
  139. $fds[$scene.'_'.$fromUid] = $frameId;
  140. RedisService::set("chats:bindFds:{$scene}_{$liveId}", $fds, 86400);
  141. RedisService::set("chats:bind:{$scene}_{$fromUid}", ['fd' => $frameId,'scene'=>$scene, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 86400);
  142. }
  143. }
  144. switch ($op) {
  145. case 'chat': // 图文聊天
  146. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  147. $chatType = isset($data['chat_type']) ? $data['chat_type'] : 1;
  148. $message = isset($data['message']) ? trim($data['message']) : '';
  149. // 发送参数验证
  150. if ($toUid <= 0 || $fromUid <= 0 || empty($message)) {
  151. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  152. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  153. return false;
  154. }
  155. // 用户私聊
  156. $fromUserName = $fromAvatar = '';
  157. $toUserName = $toAvatar = '';
  158. $fromInfo = MemberService::make()->getCacheInfo(['id'=> $fromUid,'status'=>1]);
  159. if(empty($fromInfo)){
  160. $this->info("【{$scene} {$date}】Socket:发送用户不存在,from@{$fromUid}-to@{$toUid}。");
  161. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '您的账号不可用或已冻结,请联系客服']);
  162. return false;
  163. }
  164. $toInfo = MemberService::make()->getCacheInfo(['id'=> $toUid,'status'=>1]);
  165. if(empty($toInfo)){
  166. $this->info("【{$scene} {$date}】Socket:接收用户不存在,from@{$fromUid}-to@{$toUid}。");
  167. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '对方账号不可用或无法接收消息']);
  168. return false;
  169. }
  170. if($chatType == 1){
  171. $fromUserName = isset($fromInfo['nickname'])? $fromInfo['nickname'] : $fromUid;
  172. $fromAvatar = isset($fromInfo['avatar'])? $fromInfo['avatar'] : '';
  173. $toUserName = isset($toInfo['nickname'])? $toInfo['nickname'] : $toUid;
  174. $toAvatar = isset($toInfo['avatar'])? $toInfo['avatar'] : '';
  175. }
  176. $msgData = [
  177. 'from_uid' => $fromUid,
  178. 'to_uid' => $toUid,
  179. 'type' => 9,
  180. 'msg_type' => $msgType,
  181. 'chat_type' => $chatType,
  182. 'from_user_name' => $fromUserName,
  183. 'to_user_name' => $toUserName,
  184. 'from_user_avatar' => $fromAvatar,
  185. 'to_user_avatar' => $toAvatar,
  186. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  187. 'content' => $message,
  188. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  189. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  190. 'video_id' => isset($data['video_id'])? intval($data['video_id']) : 0,
  191. 'chat_key' => $chatKey,
  192. 'create_time' => time(),
  193. 'update_time' => time(),
  194. 'is_read' => 2,
  195. 'status' => 1
  196. ];
  197. if (!$id = MessageModel::insertGetId($msgData)) {
  198. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  199. $this->sendMsg($frameId, $data);
  200. return false;
  201. }
  202. // 推送消息给对方
  203. $msgData['from_user_avatar'] = get_image_url($msgData['from_user_avatar'], $apiUrl);
  204. $msgData['to_user_avatar'] = get_image_url($msgData['to_user_avatar'], $apiUrl);
  205. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  206. $msgData['time_text'] = dateFormat($msgData['create_time']);
  207. $msgData['goods'] = [];
  208. $msgData['live_info'] = [];
  209. // 直播间信息
  210. if($msgData['live_id']){
  211. $info = LiveModel::with(['member'])->where(['id'=> $msgData['live_id'],'mark'=>1])
  212. ->select(['id','user_id','play_url','description','status'])
  213. ->first();
  214. $info = $info? $info->toArray() : [];
  215. if($info){
  216. $member = isset($info['member'])? $info['member'] : [];
  217. $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar'], $apiUrl) : get_image_url('/images/member/logo.png',$apiUrl);
  218. $info['member'] = $member;
  219. }
  220. $msgData['live_info'] = $info;
  221. }
  222. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  223. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  224. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  225. if ($toBindData && $toFd) {
  226. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  227. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  228. }
  229. break;
  230. case 'live': // 直播聊天
  231. // 推送消息给对方
  232. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  233. $message = isset($data['message']) ? trim($data['message']) : '';
  234. // 发送参数验证
  235. if ($fromUid <= 0 || $liveId<=0 || empty($message)) {
  236. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  237. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => lang('发送失败')]);
  238. return false;
  239. }
  240. $msgData = [
  241. 'from_uid' => $fromUid,
  242. 'to_uid' => $toUid,
  243. 'msg_type' => 1,
  244. 'live_id' => $liveId,
  245. 'message' => $message,
  246. 'chat_key' => $chatKey,
  247. 'create_time' => time(),
  248. 'update_time' => time(),
  249. 'status' => 1
  250. ];
  251. if (!$id = LiveChatModel::insertGetId($msgData)) {
  252. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  253. $this->sendMsg($frameId, $data);
  254. return false;
  255. }
  256. // 推送消息给对方
  257. $msgData['nickname'] = MemberModel::where(['id'=> $fromUid])->value('nickname');
  258. $msgData['time_text'] = dateFormat($msgData['create_time']);
  259. //$this->sendMsg($frameId, ['success' => true, 'op' => 'push_live', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  260. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  261. $fids = array_values($fids);
  262. $fids = array_unique($fids);
  263. if($fids){
  264. foreach($fids as $fd){
  265. $this->sendMsg($fd, ['success' => true, 'op' => 'push_live' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $fd]);
  266. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$fd}-{$liveId}。");
  267. }
  268. }
  269. break;
  270. case 'acceptor': // 承兑商
  271. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  272. $chatType = isset($data['chat_type']) ? $data['chat_type'] : 1;
  273. $message = isset($data['message']) ? trim($data['message']) : '';
  274. $fromUserName = isset($data['from_user_name']) ? trim($data['from_user_name']) : '';
  275. $fromUserAvatar = isset($data['from_user_avatar']) ? trim($data['from_user_avatar']) : '';
  276. $toUserName = isset($data['to_user_name']) ? trim($data['to_user_name']) : '';
  277. $toUserAvatar = isset($data['to_user_avatar']) ? trim($data['to_user_avatar']) : '';
  278. // 发送参数验证
  279. if ($toUid <= 0 || $fromUid <= 0 || empty($message) || empty($fromUserName) || empty($toUserName)) {
  280. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  281. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  282. return false;
  283. }
  284. $msgData = [
  285. 'from_uid' => $fromUid,
  286. 'to_uid' => $toUid,
  287. 'type' => 9,
  288. 'msg_type' => $msgType,
  289. 'chat_type' => 3,
  290. 'from_user_name' => $fromUserName,
  291. 'to_user_name' => $toUserName,
  292. 'from_user_avatar' => get_image_path($fromUserAvatar),
  293. 'to_user_avatar' => get_image_path($toUserAvatar),
  294. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  295. 'content' => $message,
  296. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  297. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  298. 'chat_key' => $chatKey,
  299. 'create_time' => time(),
  300. 'update_time' => time(),
  301. 'is_read' => 2,
  302. 'status' => 1
  303. ];
  304. if (!$id = MessageModel::insertGetId($msgData)) {
  305. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  306. $this->sendMsg($frameId, $data);
  307. return false;
  308. }
  309. // 推送消息给对方
  310. $msgData['from_user_avatar'] = $fromUserAvatar;
  311. $msgData['to_user_avatar'] = $toUserAvatar;
  312. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  313. $msgData['time_text'] = dateFormat($msgData['create_time']);
  314. $msgData['goods'] = [];
  315. $msgData['live_info'] = [];
  316. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  317. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  318. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  319. if ($toBindData && $toFd) {
  320. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  321. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  322. }
  323. break;
  324. case 'group': // 群聊
  325. $message = isset($data['message']) ? trim($data['message']) : '';
  326. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  327. $fromUserName = isset($data['from_user_name']) ? trim($data['from_user_name']) : '';
  328. $fromUserAvatar = isset($data['from_user_avatar']) ? trim($data['from_user_avatar']) : '';
  329. // 发送参数验证
  330. if ($groupId <= 0 || $fromUid <= 0 || empty($message) || empty($fromUserName)) {
  331. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$groupId}。");
  332. $this->sendMsg($frameId, ['success' => false,'op'=>'push_group', 'scene'=>$scene,'data'=>$data, 'message' => '群聊参数错误']);
  333. return false;
  334. }
  335. $msgData = [
  336. 'from_uid' => $fromUid,
  337. 'to_uid' => 0,
  338. 'type' => 9,
  339. 'msg_type' => $msgType,
  340. 'chat_type' => 0,
  341. 'from_user_name' => $fromUserName,
  342. 'to_user_name' => '',
  343. 'from_user_avatar' => get_image_path($fromUserAvatar),
  344. 'to_user_avatar' => '',
  345. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  346. 'content' => $message,
  347. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  348. 'group_id' => isset($data['group_id'])? intval($data['group_id']) : 0,
  349. 'video_id' => isset($data['video_id'])? intval($data['video_id']) : 0,
  350. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  351. 'chat_key' => $chatKey,
  352. 'create_time' => time(),
  353. 'update_time' => time(),
  354. 'is_read' => 2,
  355. 'status' => 1
  356. ];
  357. if (!$id = MessageModel::insertGetId($msgData)) {
  358. $data = ['success' => false,'op'=>'push_group','scene'=>$scene,'data'=>$msgData, 'message' => '群聊消息发送失败'];
  359. $this->sendMsg($frameId, $data);
  360. return false;
  361. }
  362. // 推送消息给对方
  363. $msgData['from_user_avatar'] = $fromUserAvatar;
  364. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  365. $msgData['time_text'] = dateFormat($msgData['create_time']);
  366. $msgData['goods'] = [];
  367. $msgData['live_info'] = [];
  368. $msgData['video_info'] = [];
  369. // $this->sendMsg($frameId, ['success' => true, 'op' => 'push_group', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  370. $fids = RedisService::get("chats:bindFds:{$scene}_{$groupId}");
  371. RedisService::keyDel("caches:messages:new_0_{$chatKey}_*");
  372. RedisService::keyDel("caches:messages:un_{$fromUid}_{$chatKey}_*");
  373. $fids = array_values($fids);
  374. $fids = array_unique($fids);
  375. if($fids){
  376. foreach($fids as $fd){
  377. $this->sendMsg($fd, ['success' => true, 'op' => 'push_group' ,'scene'=> $scene, 'data' => $msgData, 'message' => '群聊推送消息成功:' . $fd]);
  378. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$fd}-{$liveId}。");
  379. }
  380. }
  381. break;
  382. case 'login': // 登录
  383. $this->info("【{$scene} {$date}】Socket:登录成功【{$frameId}-{$fromUid}-{$op}】。");
  384. $this->sendMsg($frameId, ['success' => true,'op'=> $op, 'scene'=>$scene, 'message' => '登录成功', 'data' => $data, 't' => time()]);
  385. break;
  386. case 'live_leave': // 进入直播间消息
  387. RedisService::clear("caches:live:users_{$liveId}_{#$fromUid}");
  388. VideoCollectModel::where(['user_id'=> $fromUid,'type'=>1,'source_type'=>2,'collect_id'=>$liveId])->whereNotIn('collect_uid',[$fromUid])->update(['is_online'=>2,'update_time'=>time()]);
  389. case 'live_entry': // 进入直播间消息
  390. RedisService::clear("caches:live:users_{$liveId}_{#$fromUid}");
  391. VideoCollectModel::where(['user_id'=> $fromUid,'type'=>1,'source_type'=>2,'collect_id'=>$liveId])->whereNotIn('collect_uid',[$fromUid])->update(['is_online'=>1,'update_time'=>time()]);
  392. case 'live_like': // 进入直播间消息
  393. case 'follow': // 关注主播消息
  394. case 'gift': // 打赏礼物消息
  395. $types = ['live_entry'=>'进入直播间消息','live_like'=>'点赞消息','follow'=>'关注消息','gift'=>'礼物消息'];
  396. $typeName = isset($types[$op])? $types[$op] : '直播间消息';
  397. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  398. $fids = array_values($fids);
  399. $fids = array_unique($fids);
  400. if($fids){
  401. foreach($fids as $fd){
  402. $this->sendMsg($fd, ['success' => true,'op'=> $op, 'scene'=>$scene, 'data' => $data, 'message' => $typeName, 't' => time()]);
  403. }
  404. }
  405. break;
  406. default:
  407. $this->sendMsg($frameId, ['success' => false, 'message' => 'ok', 'scene'=>$scene, 'data' => $data, 't' => time()]);
  408. break;
  409. }
  410. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理成功");
  411. } catch (\Exception $exception) {
  412. RedisService::set("caches:sockets:error_{$frameId}", ['error' => $exception->getMessage(),'trace'=>$exception->getTrace(), 'date' => $date], 7200);
  413. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理错误 " . $exception->getMessage());
  414. }
  415. }
  416. /**
  417. * 签名验证
  418. * @param $data
  419. * @return bool
  420. */
  421. public function checkSign($data)
  422. {
  423. $checkSign = isset($data['sign']) ? $data['sign'] : '';
  424. $sign = getSign($data);
  425. if ($sign != $checkSign) {
  426. return false;
  427. }
  428. return true;
  429. }
  430. /**
  431. * 推送消息
  432. * @param $fd
  433. * @param $op
  434. * @param $data
  435. */
  436. public function sendMsg($fd, $data)
  437. {
  438. $date = date('Y-m-d H:i:s');
  439. try {
  440. if (!RedisService::exists("chats:frames:" . $fd)) {
  441. $this->info("【{$date}】Socket:客户端【{$fd}】推送用户已经掉线 ");
  442. return false;
  443. }
  444. $this->ws->push($fd, json_encode($data, 256));
  445. } catch (\Exception $exception) {
  446. $this->info("【{$date}】Socket:客户端【{$fd}】消息处理错误 " . $exception->getMessage());
  447. }
  448. }
  449. /**
  450. * 接收请求
  451. * @param $request
  452. * @param $response
  453. */
  454. public function request($request, $response)
  455. {
  456. }
  457. /**
  458. * 关闭连接
  459. * @param $ws
  460. * @param $fd
  461. */
  462. public function close($ws, $fd = '')
  463. {
  464. $date = date('Y-m-d H:i:s');
  465. RedisService::clear("chats:frames:" . $fd);
  466. $this->info("【{$date}】Socket:客户端【{$fd}】连接关闭");
  467. $this->ws->close($fd);
  468. }
  469. /**
  470. * 停止运行
  471. */
  472. public function stop()
  473. {
  474. // 直接杀
  475. $stoSh = base_path().'/crontab/socketStop.sh';
  476. if(file_exists($stoSh) && function_exists('exec')){
  477. exec("{$stoSh}");
  478. }
  479. echo "$stoSh\n";
  480. echo "socket stop success...\n";
  481. if ($this->ws) {
  482. $date = date('Y-m-d H:i:s');
  483. $this->info("【{$date}】Socket:停止运行服务");
  484. $this->ws->close();
  485. }
  486. }
  487. /**
  488. * 消息
  489. * @param string $data
  490. */
  491. public function info($data,$verbosity=true)
  492. {
  493. \logger()->channel('swoole')->info($data);
  494. if(env('SWOOLE_LOG', true) && $verbosity){
  495. parent::info($data);
  496. }
  497. }
  498. }