SocketServer.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. $apiUrl = env('APP_URL','');
  123. $chatKey = isset($data['chat_key']) ? trim($data['chat_key']) : '';
  124. $chatKey = $chatKey ? $chatKey : getChatKey($fromUid, $toUid);
  125. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  126. try {
  127. // 推送Fd处理
  128. if ($fromUid && $frameId) {
  129. $fds = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  130. $fds = $fds? $fds : [];
  131. $fds[$scene.'_'.$fromUid] = $frameId;
  132. RedisService::set("chats:bindFds:{$scene}_{$liveId}", $fds, 86400);
  133. RedisService::set("chats:bind:{$scene}_{$fromUid}", ['fd' => $frameId,'scene'=>$scene, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 86400);
  134. }
  135. switch ($op) {
  136. case 'chat': // 图文聊天
  137. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  138. $chatType = isset($data['chat_type']) ? $data['chat_type'] : 1;
  139. $message = isset($data['message']) ? trim($data['message']) : '';
  140. // 发送参数验证
  141. if ($toUid <= 0 || $fromUid <= 0 || empty($message)) {
  142. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  143. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  144. return false;
  145. }
  146. // 用户私聊
  147. $fromUserName = $fromAvatar = '';
  148. $toUserName = $toAvatar = '';
  149. $fromInfo = MemberService::make()->getCacheInfo(['id'=> $fromUid,'status'=>1]);
  150. if(empty($fromInfo)){
  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. $toInfo = MemberService::make()->getCacheInfo(['id'=> $toUid,'status'=>1]);
  156. if(empty($toInfo)){
  157. $this->info("【{$scene} {$date}】Socket:接收用户不存在,from@{$fromUid}-to@{$toUid}。");
  158. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '对方账号不可用或无法接收消息']);
  159. return false;
  160. }
  161. if($chatType == 1){
  162. $fromUserName = isset($fromInfo['nickname'])? $fromInfo['nickname'] : $fromUid;
  163. $fromAvatar = isset($fromInfo['avatar'])? $fromInfo['avatar'] : '';
  164. $toUserName = isset($toInfo['nickname'])? $toInfo['nickname'] : $toUid;
  165. $toAvatar = isset($toInfo['avatar'])? $toInfo['avatar'] : '';
  166. }
  167. $msgData = [
  168. 'from_uid' => $fromUid,
  169. 'to_uid' => $toUid,
  170. 'type' => 9,
  171. 'msg_type' => $msgType,
  172. 'chat_type' => $chatType,
  173. 'from_user_name' => $fromUserName,
  174. 'to_user_name' => $toUserName,
  175. 'from_user_avatar' => $fromAvatar,
  176. 'to_user_avatar' => $toAvatar,
  177. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  178. 'content' => $message,
  179. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  180. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  181. 'chat_key' => $chatKey,
  182. 'create_time' => time(),
  183. 'update_time' => time(),
  184. 'is_read' => 2,
  185. 'status' => 1
  186. ];
  187. if (!$id = MessageModel::insertGetId($msgData)) {
  188. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  189. $this->sendMsg($frameId, $data);
  190. return false;
  191. }
  192. // 推送消息给对方
  193. $msgData['from_user_avatar'] = get_image_url($msgData['from_user_avatar'], $apiUrl);
  194. $msgData['to_user_avatar'] = get_image_url($msgData['to_user_avatar'], $apiUrl);
  195. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  196. $msgData['time_text'] = dateFormat($msgData['create_time']);
  197. $msgData['goods'] = [];
  198. $msgData['live_info'] = [];
  199. // 直播间信息
  200. if($msgData['live_id']){
  201. $info = LiveModel::with(['member'])->where(['id'=> $msgData['live_id'],'mark'=>1])
  202. ->select(['id','user_id','play_url','description','status'])
  203. ->first();
  204. $info = $info? $info->toArray() : [];
  205. if($info){
  206. $member = isset($info['member'])? $info['member'] : [];
  207. $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar'], $apiUrl) : get_image_url('/images/member/logo.png',$apiUrl);
  208. $info['member'] = $member;
  209. }
  210. $msgData['live_info'] = $info;
  211. }
  212. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  213. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  214. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  215. if ($toBindData && $toFd) {
  216. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  217. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  218. }
  219. break;
  220. case 'live': // 直播聊天
  221. // 推送消息给对方
  222. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  223. $message = isset($data['message']) ? trim($data['message']) : '';
  224. // 发送参数验证
  225. if ($fromUid <= 0 || $liveId<=0 || empty($message)) {
  226. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  227. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => lang('发送失败')]);
  228. return false;
  229. }
  230. $msgData = [
  231. 'from_uid' => $fromUid,
  232. 'to_uid' => $toUid,
  233. 'msg_type' => 1,
  234. 'live_id' => $liveId,
  235. 'message' => $message,
  236. 'chat_key' => $chatKey,
  237. 'create_time' => time(),
  238. 'update_time' => time(),
  239. 'status' => 1
  240. ];
  241. if (!$id = LiveChatModel::insertGetId($msgData)) {
  242. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  243. $this->sendMsg($frameId, $data);
  244. return false;
  245. }
  246. // 推送消息给对方
  247. $msgData['nickname'] = MemberModel::where(['id'=> $fromUid])->value('nickname');
  248. $msgData['time_text'] = dateFormat($msgData['create_time']);
  249. //$this->sendMsg($frameId, ['success' => true, 'op' => 'push_live', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  250. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  251. $fids = array_values($fids);
  252. $fids = array_unique($fids);
  253. if($fids){
  254. foreach($fids as $fd){
  255. $this->sendMsg($fd, ['success' => true, 'op' => 'push_live' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $fd]);
  256. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$fd}-{$liveId}。");
  257. }
  258. }
  259. break;
  260. case 'acceptor': // 承兑商
  261. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  262. $chatType = isset($data['chat_type']) ? $data['chat_type'] : 1;
  263. $message = isset($data['message']) ? trim($data['message']) : '';
  264. $fromUserName = isset($data['from_user_name']) ? trim($data['from_user_name']) : '';
  265. $fromUserAvatar = isset($data['from_user_avatar']) ? trim($data['from_user_avatar']) : '';
  266. $toUserName = isset($data['to_user_name']) ? trim($data['to_user_name']) : '';
  267. $toUserAvatar = isset($data['to_user_avatar']) ? trim($data['to_user_avatar']) : '';
  268. // 发送参数验证
  269. if ($toUid <= 0 || $fromUid <= 0 || empty($message) || empty($fromUserName) || empty($toUserName)) {
  270. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  271. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  272. return false;
  273. }
  274. $msgData = [
  275. 'from_uid' => $fromUid,
  276. 'to_uid' => $toUid,
  277. 'type' => 9,
  278. 'msg_type' => $msgType,
  279. 'chat_type' => 3,
  280. 'from_user_name' => $fromUserName,
  281. 'to_user_name' => $toUserName,
  282. 'from_user_avatar' => get_image_path($fromUserAvatar),
  283. 'to_user_avatar' => get_image_path($toUserAvatar),
  284. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  285. 'content' => $message,
  286. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  287. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  288. 'chat_key' => $chatKey,
  289. 'create_time' => time(),
  290. 'update_time' => time(),
  291. 'is_read' => 2,
  292. 'status' => 1
  293. ];
  294. if (!$id = MessageModel::insertGetId($msgData)) {
  295. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  296. $this->sendMsg($frameId, $data);
  297. return false;
  298. }
  299. // 推送消息给对方
  300. $msgData['from_user_avatar'] = $fromUserAvatar;
  301. $msgData['to_user_avatar'] = $toUserAvatar;
  302. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  303. $msgData['time_text'] = dateFormat($msgData['create_time']);
  304. $msgData['goods'] = [];
  305. $msgData['live_info'] = [];
  306. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  307. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  308. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  309. if ($toBindData && $toFd) {
  310. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  311. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  312. }
  313. break;
  314. case 'login': // 登录
  315. $this->info("【{$scene} {$date}】Socket:登录成功【{$frameId}-{$fromUid}-{$op}】。");
  316. $this->sendMsg($frameId, ['success' => true,'op'=> $op, 'scene'=>$scene, 'message' => '登录成功', 'data' => $data, 't' => time()]);
  317. break;
  318. case 'live_leave': // 进入直播间消息
  319. RedisService::clear("caches:live:users_{$liveId}_{#$fromUid}");
  320. VideoCollectModel::where(['user_id'=> $fromUid,'type'=>1,'source_type'=>2,'collect_id'=>$liveId])->whereNotIn('collect_uid',[$fromUid])->update(['is_online'=>2,'update_time'=>time()]);
  321. case 'live_entry': // 进入直播间消息
  322. RedisService::clear("caches:live:users_{$liveId}_{#$fromUid}");
  323. VideoCollectModel::where(['user_id'=> $fromUid,'type'=>1,'source_type'=>2,'collect_id'=>$liveId])->whereNotIn('collect_uid',[$fromUid])->update(['is_online'=>1,'update_time'=>time()]);
  324. case 'live_like': // 进入直播间消息
  325. case 'follow': // 关注主播消息
  326. case 'gift': // 打赏礼物消息
  327. $types = ['live_entry'=>'进入直播间消息','live_like'=>'点赞消息','follow'=>'关注消息','gift'=>'礼物消息'];
  328. $typeName = isset($types[$op])? $types[$op] : '直播间消息';
  329. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  330. $fids = array_values($fids);
  331. $fids = array_unique($fids);
  332. if($fids){
  333. foreach($fids as $fd){
  334. $this->sendMsg($fd, ['success' => true,'op'=> $op, 'scene'=>$scene, 'data' => $data, 'message' => $typeName, 't' => time()]);
  335. }
  336. }
  337. break;
  338. default:
  339. $this->sendMsg($frameId, ['success' => false, 'message' => 'ok', 'scene'=>$scene, 'data' => $data, 't' => time()]);
  340. break;
  341. }
  342. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理成功");
  343. } catch (\Exception $exception) {
  344. RedisService::set("caches:sockets:error_{$frameId}", ['error' => $exception->getMessage(),'trace'=>$exception->getTrace(), 'date' => $date], 7200);
  345. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理错误 " . $exception->getMessage());
  346. }
  347. }
  348. /**
  349. * 签名验证
  350. * @param $data
  351. * @return bool
  352. */
  353. public function checkSign($data)
  354. {
  355. $checkSign = isset($data['sign']) ? $data['sign'] : '';
  356. $sign = getSign($data);
  357. if ($sign != $checkSign) {
  358. return false;
  359. }
  360. return true;
  361. }
  362. /**
  363. * 推送消息
  364. * @param $fd
  365. * @param $op
  366. * @param $data
  367. */
  368. public function sendMsg($fd, $data)
  369. {
  370. $date = date('Y-m-d H:i:s');
  371. try {
  372. if (!RedisService::exists("chats:frames:" . $fd)) {
  373. $this->info("【{$date}】Socket:客户端【{$fd}】推送用户已经掉线 ");
  374. return false;
  375. }
  376. $this->ws->push($fd, json_encode($data, 256));
  377. } catch (\Exception $exception) {
  378. $this->info("【{$date}】Socket:客户端【{$fd}】消息处理错误 " . $exception->getMessage());
  379. }
  380. }
  381. /**
  382. * 接收请求
  383. * @param $request
  384. * @param $response
  385. */
  386. public function request($request, $response)
  387. {
  388. }
  389. /**
  390. * 关闭连接
  391. * @param $ws
  392. * @param $fd
  393. */
  394. public function close($ws, $fd = '')
  395. {
  396. $date = date('Y-m-d H:i:s');
  397. RedisService::clear("chats:frames:" . $fd);
  398. $this->info("【{$date}】Socket:客户端【{$fd}】连接关闭");
  399. $this->ws->close($fd);
  400. }
  401. /**
  402. * 停止运行
  403. */
  404. public function stop()
  405. {
  406. // 直接杀
  407. $stoSh = base_path().'/crontab/socketStop.sh';
  408. if(file_exists($stoSh) && function_exists('exec')){
  409. exec("{$stoSh}");
  410. }
  411. echo "$stoSh\n";
  412. echo "socket stop success...\n";
  413. if ($this->ws) {
  414. $date = date('Y-m-d H:i:s');
  415. $this->info("【{$date}】Socket:停止运行服务");
  416. $this->ws->close();
  417. }
  418. }
  419. /**
  420. * 消息
  421. * @param string $data
  422. */
  423. public function info($data,$verbosity=true)
  424. {
  425. \logger()->channel('swoole')->info($data);
  426. if(env('SWOOLE_LOG', true) && $verbosity){
  427. parent::info($data);
  428. }
  429. }
  430. }