SocketServer.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. $this->ws->push($request->fd, json_encode(['success' => 'true', 'op' => 'conn', 'message' => '连接成功', 'fd' => $request->fd], 256));
  87. $this->info("【{$date}】Socket:客户端【{$request->fd}】连接成功");
  88. }
  89. /**
  90. * 接收消息
  91. * @param $ws
  92. * @param $frame
  93. */
  94. public function message($ws, $frame)
  95. {
  96. $date = date('Y-m-d H:i:s');
  97. RedisService::set("chats:frames:" . $frame->fd, json_decode($frame->data, true), 86400);
  98. if ($frame->data == 'ping') {
  99. $this->ws->push($frame->fd, 'pong');
  100. $this->info("【{$date}】Socket:客户端【{$frame->fd}】心跳包",false);
  101. return false;
  102. }
  103. // 消息处理
  104. $frameId = $frame->fd;
  105. $data = $frame->data ? json_decode($frame->data, true) : [];
  106. $fromUid = isset($data['from_uid']) ? intval($data['from_uid']) : 0;
  107. $token = isset($data['token']) ? $data['token'] : '';
  108. $op = isset($data['op']) ? $data['op'] : '';
  109. $scene = isset($data['scene']) && $data['scene'] ? $data['scene'] : 'chat';
  110. $jwt = new Jwt();
  111. $userId = $jwt->verifyToken($token);
  112. if ($userId != $fromUid) {
  113. $this->info("【{$scene} {$date}】Socket:签名失败【{$frameId}-{$fromUid}】");
  114. return false;
  115. }
  116. $uuid = isset($data['uuid']) ? $data['uuid'] : uniqid();
  117. $toUid = isset($data['to_uid']) ? intval($data['to_uid']) : 0;
  118. $apiUrl = env('APP_URL','');
  119. $chatKey = isset($data['chat_key']) ? trim($data['chat_key']) : '';
  120. $chatKey = $chatKey ? $chatKey : getChatKey($fromUid, $toUid);
  121. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  122. try {
  123. // 推送Fd处理
  124. if ($fromUid && $frameId) {
  125. $fds = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  126. $fds = $fds? $fds : [];
  127. $fds[$scene.'_'.$fromUid] = $frameId;
  128. RedisService::set("chats:bindFds:{$scene}_{$liveId}", $fds, 86400);
  129. RedisService::set("chats:bind:{$scene}_{$fromUid}", ['fd' => $frameId,'scene'=>$scene, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 86400);
  130. }
  131. switch ($op) {
  132. case 'chat': // 图文聊天
  133. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  134. $chatType = isset($data['chat_type']) ? $data['chat_type'] : 1;
  135. $message = isset($data['message']) ? trim($data['message']) : '';
  136. // 发送参数验证
  137. if ($toUid <= 0 || $fromUid <= 0 || empty($message)) {
  138. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  139. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  140. return false;
  141. }
  142. // 用户私聊
  143. $fromUserName = $fromAvatar = '';
  144. $toUserName = $toAvatar = '';
  145. $fromInfo = MemberService::make()->getCacheInfo(['id'=> $fromUid,'status'=>1]);
  146. if(empty($fromInfo)){
  147. $this->info("【{$scene} {$date}】Socket:发送用户不存在,from@{$fromUid}-to@{$toUid}。");
  148. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '您的账号不可用或已冻结,请联系客服']);
  149. return false;
  150. }
  151. $toInfo = MemberService::make()->getCacheInfo(['id'=> $toUid,'status'=>1]);
  152. if(empty($toInfo)){
  153. $this->info("【{$scene} {$date}】Socket:接收用户不存在,from@{$fromUid}-to@{$toUid}。");
  154. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '对方账号不可用或无法接收消息']);
  155. return false;
  156. }
  157. if($chatType == 1){
  158. $fromUserName = isset($fromInfo['nickname'])? $fromInfo['nickname'] : $fromUid;
  159. $fromAvatar = isset($fromInfo['avatar'])? $fromInfo['avatar'] : '';
  160. $toUserName = isset($toInfo['nickname'])? $toInfo['nickname'] : $toUid;
  161. $toAvatar = isset($toInfo['avatar'])? $toInfo['avatar'] : '';
  162. }
  163. $msgData = [
  164. 'from_uid' => $fromUid,
  165. 'to_uid' => $toUid,
  166. 'type' => 9,
  167. 'msg_type' => $msgType,
  168. 'chat_type' => $chatType,
  169. 'from_user_name' => $fromUserName,
  170. 'to_user_name' => $toUserName,
  171. 'from_user_avatar' => $fromAvatar,
  172. 'to_user_avatar' => $toAvatar,
  173. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  174. 'content' => $message,
  175. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  176. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  177. 'chat_key' => $chatKey,
  178. 'create_time' => time(),
  179. 'update_time' => time(),
  180. 'is_read' => 2,
  181. 'status' => 1
  182. ];
  183. if (!$id = MessageModel::insertGetId($msgData)) {
  184. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  185. $this->sendMsg($frameId, $data);
  186. return false;
  187. }
  188. // 推送消息给对方
  189. $msgData['from_user_avatar'] = get_image_url($msgData['from_user_avatar'], $apiUrl);
  190. $msgData['to_user_avatar'] = get_image_url($msgData['to_user_avatar'], $apiUrl);
  191. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  192. $msgData['time_text'] = dateFormat($msgData['create_time']);
  193. $msgData['goods'] = [];
  194. $msgData['live_info'] = [];
  195. // 直播间信息
  196. if($msgData['live_id']){
  197. $info = LiveModel::with(['member'])->where(['id'=> $msgData['live_id'],'mark'=>1])
  198. ->select(['id','user_id','play_url','description','status'])
  199. ->first();
  200. $info = $info? $info->toArray() : [];
  201. if($info){
  202. $member = isset($info['member'])? $info['member'] : [];
  203. $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar'], $apiUrl) : get_image_url('/images/member/logo.png',$apiUrl);
  204. $info['member'] = $member;
  205. }
  206. $msgData['live_info'] = $info;
  207. }
  208. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  209. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  210. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  211. if ($toBindData && $toFd) {
  212. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  213. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  214. }
  215. break;
  216. case 'live': // 直播聊天
  217. // 推送消息给对方
  218. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  219. $message = isset($data['message']) ? trim($data['message']) : '';
  220. // 发送参数验证
  221. if ($fromUid <= 0 || $liveId<=0 || empty($message)) {
  222. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  223. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => lang('发送失败')]);
  224. return false;
  225. }
  226. $msgData = [
  227. 'from_uid' => $fromUid,
  228. 'to_uid' => $toUid,
  229. 'msg_type' => 1,
  230. 'live_id' => $liveId,
  231. 'message' => $message,
  232. 'chat_key' => $chatKey,
  233. 'create_time' => time(),
  234. 'update_time' => time(),
  235. 'status' => 1
  236. ];
  237. if (!$id = LiveChatModel::insertGetId($msgData)) {
  238. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  239. $this->sendMsg($frameId, $data);
  240. return false;
  241. }
  242. // 推送消息给对方
  243. $msgData['nickname'] = MemberModel::where(['id'=> $fromUid])->value('nickname');
  244. $msgData['time_text'] = dateFormat($msgData['create_time']);
  245. //$this->sendMsg($frameId, ['success' => true, 'op' => 'push_live', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  246. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  247. $fids = array_values($fids);
  248. $fids = array_unique($fids);
  249. if($fids){
  250. foreach($fids as $fd){
  251. $this->sendMsg($fd, ['success' => true, 'op' => 'push_live' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $fd]);
  252. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$fd}-{$liveId}。");
  253. }
  254. }
  255. break;
  256. case 'login': // 登录
  257. $this->info("【{$scene} {$date}】Socket:登录成功【{$frameId}-{$fromUid}-{$op}】。");
  258. $this->sendMsg($frameId, ['success' => true,'op'=> $op, 'scene'=>$scene, 'message' => '登录成功', 'data' => $data, 't' => time()]);
  259. break;
  260. case 'live_leave': // 进入直播间消息
  261. VideoCollectModel::where(['iser_id'=> $fromUid,'type'=>1,'source_type'=>2,'collect_id'=>$liveId])->update(['is_online'=>2,'update_time'=>time()]);
  262. case 'live_entry': // 进入直播间消息
  263. VideoCollectModel::where(['iser_id'=> $fromUid,'type'=>1,'source_type'=>2,'collect_id'=>$liveId])->update(['is_online'=>1,'update_time'=>time()]);
  264. case 'live_like': // 进入直播间消息
  265. case 'follow': // 关注主播消息
  266. case 'gift': // 打赏礼物消息
  267. $types = ['live_entry'=>'进入直播间消息','live_like'=>'点赞消息','follow'=>'关注消息','gift'=>'礼物消息'];
  268. $typeName = isset($types[$op])? $types[$op] : '直播间消息';
  269. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  270. $fids = array_values($fids);
  271. $fids = array_unique($fids);
  272. if($fids){
  273. foreach($fids as $fd){
  274. $this->sendMsg($fd, ['success' => true,'op'=> $op, 'scene'=>$scene, 'data' => $data, 'message' => $typeName, 't' => time()]);
  275. }
  276. }
  277. break;
  278. default:
  279. $this->sendMsg($frameId, ['success' => false, 'message' => 'ok', 'scene'=>$scene, 'data' => $data, 't' => time()]);
  280. break;
  281. }
  282. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理成功");
  283. } catch (\Exception $exception) {
  284. RedisService::set("caches:sockets:error_{$frameId}", ['error' => $exception->getMessage(),'trace'=>$exception->getTrace(), 'date' => $date], 7200);
  285. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理错误 " . $exception->getMessage());
  286. }
  287. }
  288. /**
  289. * 签名验证
  290. * @param $data
  291. * @return bool
  292. */
  293. public function checkSign($data)
  294. {
  295. $checkSign = isset($data['sign']) ? $data['sign'] : '';
  296. $sign = getSign($data);
  297. if ($sign != $checkSign) {
  298. return false;
  299. }
  300. return true;
  301. }
  302. /**
  303. * 推送消息
  304. * @param $fd
  305. * @param $op
  306. * @param $data
  307. */
  308. public function sendMsg($fd, $data)
  309. {
  310. $date = date('Y-m-d H:i:s');
  311. try {
  312. if (!RedisService::exists("chats:frames:" . $fd)) {
  313. $this->info("【{$date}】Socket:客户端【{$fd}】推送用户已经掉线 ");
  314. return false;
  315. }
  316. $this->ws->push($fd, json_encode($data, 256));
  317. } catch (\Exception $exception) {
  318. $this->info("【{$date}】Socket:客户端【{$fd}】消息处理错误 " . $exception->getMessage());
  319. }
  320. }
  321. /**
  322. * 接收请求
  323. * @param $request
  324. * @param $response
  325. */
  326. public function request($request, $response)
  327. {
  328. }
  329. /**
  330. * 关闭连接
  331. * @param $ws
  332. * @param $fd
  333. */
  334. public function close($ws, $fd = '')
  335. {
  336. $date = date('Y-m-d H:i:s');
  337. RedisService::clear("chats:frames:" . $fd);
  338. $this->info("【{$date}】Socket:客户端【{$fd}】连接关闭");
  339. $this->ws->close($fd);
  340. }
  341. /**
  342. * 停止运行
  343. */
  344. public function stop()
  345. {
  346. // 直接杀
  347. $stoSh = base_path().'/crontab/socketStop.sh';
  348. if(file_exists($stoSh) && function_exists('exec')){
  349. exec("{$stoSh}");
  350. }
  351. echo "$stoSh\n";
  352. echo "socket stop success...\n";
  353. if ($this->ws) {
  354. $date = date('Y-m-d H:i:s');
  355. $this->info("【{$date}】Socket:停止运行服务");
  356. $this->ws->close();
  357. }
  358. }
  359. /**
  360. * 消息
  361. * @param string $data
  362. */
  363. public function info($data,$verbosity=true)
  364. {
  365. \logger()->channel('swoole')->info($data);
  366. if(env('SWOOLE_LOG', true) && $verbosity){
  367. parent::info($data);
  368. }
  369. }
  370. }