SocketServer.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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\Services\Api\MemberService;
  9. use App\Services\RedisService;
  10. use Illuminate\Console\Command;
  11. use Monolog\Logger;
  12. class SocketServer extends Command
  13. {
  14. public $ws;
  15. /**
  16. * The name and signature of the console command.
  17. *
  18. * @var string
  19. */
  20. protected $signature = 'swoole:socket {op?}';
  21. /**
  22. * The console command description.
  23. *
  24. * @var string
  25. */
  26. protected $description = 'Chat server run';
  27. protected $logger = null;
  28. /**
  29. * Create a new command instance.
  30. *
  31. * @return void
  32. */
  33. public function __construct()
  34. {
  35. parent::__construct();
  36. }
  37. /**
  38. * Execute the console command.
  39. *
  40. * @return mixed
  41. */
  42. public function handle()
  43. {
  44. $op = $this->argument('op');
  45. $op = $op ? $op : 'start';
  46. if ($op == 'start') {
  47. echo "swoole socket service start ...\n";
  48. $this->start();
  49. } else if ($op == 'stop') {
  50. echo "swoole socket service stop ...\n";
  51. $this->stop();
  52. }
  53. }
  54. /**
  55. * 运行
  56. */
  57. public function start()
  58. {
  59. try {
  60. //创建websocket服务器对象,监听0.0.0.0:7104端口
  61. $this->ws = new \Swoole\WebSocket\Server("0.0.0.0", env('SOCKET_PORT', '6530'));
  62. //监听WebSocket连接打开事件
  63. $this->ws->on('open', [$this, 'open']);
  64. //监听WebSocket消息事件
  65. $this->ws->on('message', [$this, 'message']);
  66. //监听WebSocket主动推送消息事件
  67. $this->ws->on('request', [$this, 'request']);
  68. //监听WebSocket连接关闭事件
  69. $this->ws->on('close', [$this, 'close']);
  70. $this->ws->start();
  71. } catch (\Exception $exception) {
  72. $date = date('Y-m-d H:i:s');
  73. RedisService::set("caches:sockets:error", $exception->getMessage(), 600);
  74. $this->info("【{$date}】Socket:运行异常=》" . $exception->getMessage());
  75. }
  76. }
  77. /**
  78. * 建立连接
  79. * @param $ws
  80. * @param $request
  81. */
  82. public function open($ws, $request)
  83. {
  84. $date = date('Y-m-d H:i:s');
  85. $this->ws->push($request->fd, json_encode(['success' => 'true', 'op' => 'conn', 'message' => '连接成功', 'fd' => $request->fd], 256));
  86. $this->info("【{$date}】Socket:客户端【{$request->fd}】连接成功");
  87. }
  88. /**
  89. * 接收消息
  90. * @param $ws
  91. * @param $frame
  92. */
  93. public function message($ws, $frame)
  94. {
  95. $date = date('Y-m-d H:i:s');
  96. RedisService::set("chats:frames:" . $frame->fd, json_decode($frame->data, true), 86400);
  97. if ($frame->data == 'ping') {
  98. $this->ws->push($frame->fd, 'pong');
  99. $this->info("【{$date}】Socket:客户端【{$frame->fd}】心跳包",false);
  100. return false;
  101. }
  102. // 消息处理
  103. $frameId = $frame->fd;
  104. $data = $frame->data ? json_decode($frame->data, true) : [];
  105. $fromUid = isset($data['from_uid']) ? intval($data['from_uid']) : 0;
  106. $token = isset($data['token']) ? $data['token'] : '';
  107. $op = isset($data['op']) ? $data['op'] : '';
  108. $scene = isset($data['scene']) && $data['scene'] ? $data['scene'] : 'chat';
  109. $jwt = new Jwt();
  110. $userId = $jwt->verifyToken($token);
  111. if ($userId != $fromUid) {
  112. $this->info("【{$scene} {$date}】Socket:签名失败【{$frameId}-{$fromUid}】");
  113. return false;
  114. }
  115. $uuid = isset($data['uuid']) ? $data['uuid'] : uniqid();
  116. $toUid = isset($data['to_uid']) ? intval($data['to_uid']) : 0;
  117. $apiUrl = env('APP_URL','');
  118. $chatKey = isset($data['chat_key']) ? trim($data['chat_key']) : '';
  119. $chatKey = $chatKey ? $chatKey : getChatKey($fromUid, $toUid);
  120. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  121. try {
  122. // 推送Fd处理
  123. if ($fromUid && $frameId) {
  124. $fds = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  125. $fds = $fds? $fds : [];
  126. $fds[$scene.'_'.$fromUid] = $frameId;
  127. RedisService::set("chats:bindFds:{$scene}_{$liveId}", $fds, 86400);
  128. RedisService::set("chats:bind:{$scene}_{$fromUid}", ['fd' => $frameId,'scene'=>$scene, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 86400);
  129. }
  130. switch ($op) {
  131. case 'chat': // 图文聊天
  132. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  133. $chatType = isset($data['chat_type']) ? $data['chat_type'] : 1;
  134. $message = isset($data['message']) ? trim($data['message']) : '';
  135. // 发送参数验证
  136. if ($toUid <= 0 || $fromUid <= 0 || empty($message)) {
  137. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  138. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '参数错误']);
  139. return false;
  140. }
  141. // 用户私聊
  142. $fromUserName = $fromAvatar = '';
  143. $toUserName = $toAvatar = '';
  144. $fromInfo = MemberService::make()->getCacheInfo(['id'=> $fromUid,'status'=>1]);
  145. if(empty($fromInfo)){
  146. $this->info("【{$scene} {$date}】Socket:发送用户不存在,from@{$fromUid}-to@{$toUid}。");
  147. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '您的账号不可用或已冻结,请联系客服']);
  148. return false;
  149. }
  150. $toInfo = MemberService::make()->getCacheInfo(['id'=> $toUid,'status'=>1]);
  151. if(empty($toInfo)){
  152. $this->info("【{$scene} {$date}】Socket:接收用户不存在,from@{$fromUid}-to@{$toUid}。");
  153. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => '对方账号不可用或无法接收消息']);
  154. return false;
  155. }
  156. if($chatType == 1){
  157. $fromUserName = isset($fromInfo['nickname'])? $fromInfo['nickname'] : $fromUid;
  158. $fromAvatar = isset($fromInfo['avatar'])? $fromInfo['avatar'] : '';
  159. $toUserName = isset($toInfo['nickname'])? $toInfo['nickname'] : $toUid;
  160. $toAvatar = isset($toInfo['avatar'])? $toInfo['avatar'] : '';
  161. }
  162. $msgData = [
  163. 'from_uid' => $fromUid,
  164. 'to_uid' => $toUid,
  165. 'type' => 9,
  166. 'msg_type' => $msgType,
  167. 'chat_type' => $chatType,
  168. 'from_user_name' => $fromUserName,
  169. 'to_user_name' => $toUserName,
  170. 'from_user_avatar' => $fromAvatar,
  171. 'to_user_avatar' => $toAvatar,
  172. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  173. 'content' => $message,
  174. 'goods_id' => isset($data['goods_id'])? intval($data['goods_id']) : 0,
  175. 'live_id' => isset($data['live_id'])? intval($data['live_id']) : 0,
  176. 'chat_key' => $chatKey,
  177. 'create_time' => time(),
  178. 'update_time' => time(),
  179. 'is_read' => 2,
  180. 'status' => 1
  181. ];
  182. if (!$id = MessageModel::insertGetId($msgData)) {
  183. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  184. $this->sendMsg($frameId, $data);
  185. return false;
  186. }
  187. // 推送消息给对方
  188. $msgData['from_user_avatar'] = get_image_url($msgData['from_user_avatar'], $apiUrl);
  189. $msgData['to_user_avatar'] = get_image_url($msgData['to_user_avatar'], $apiUrl);
  190. $msgData['content'] = $msgType == 2? get_images_preview(json_decode($msgData['content'],true),'', $apiUrl) : $msgData['content'];
  191. $msgData['time_text'] = dateFormat($msgData['create_time']);
  192. $msgData['goods'] = [];
  193. $msgData['live_info'] = [];
  194. // 直播间信息
  195. if($msgData['live_id']){
  196. $info = LiveModel::with(['member'])->where(['id'=> $msgData['live_id'],'mark'=>1])
  197. ->select(['id','user_id','play_url','description','status'])
  198. ->first();
  199. $info = $info? $info->toArray() : [];
  200. if($info){
  201. $member = isset($info['member'])? $info['member'] : [];
  202. $member['avatar'] = isset($member['avatar']) && $member['avatar']? get_image_url($member['avatar'], $apiUrl) : get_image_url('/images/member/logo.png',$apiUrl);
  203. $info['member'] = $member;
  204. }
  205. $msgData['live_info'] = $info;
  206. }
  207. $this->sendMsg($frameId, ['success' => true, 'op' => 'push', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  208. $toBindData = RedisService::get("chats:bind:{$scene}_{$toUid}");
  209. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  210. if ($toBindData && $toFd) {
  211. $this->sendMsg($toFd, ['success' => true, 'op' => 'push' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $toFd]);
  212. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  213. }
  214. break;
  215. case 'live': // 直播聊天
  216. // 推送消息给对方
  217. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  218. $message = isset($data['message']) ? trim($data['message']) : '';
  219. // 发送参数验证
  220. if ($fromUid <= 0 || $liveId<=0 || empty($message)) {
  221. $this->info("【{$scene} {$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  222. $this->sendMsg($frameId, ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$data, 'message' => lang('发送失败')]);
  223. return false;
  224. }
  225. $msgData = [
  226. 'from_uid' => $fromUid,
  227. 'to_uid' => $toUid,
  228. 'msg_type' => 1,
  229. 'live_id' => $liveId,
  230. 'message' => $message,
  231. 'chat_key' => $chatKey,
  232. 'create_time' => time(),
  233. 'update_time' => time(),
  234. 'status' => 1
  235. ];
  236. if (!$id = LiveChatModel::insertGetId($msgData)) {
  237. $data = ['success' => false,'op'=>'push','scene'=>$scene,'data'=>$msgData, 'message' => '消息发送失败'];
  238. $this->sendMsg($frameId, $data);
  239. return false;
  240. }
  241. // 推送消息给对方
  242. $msgData['nickname'] = MemberModel::where(['id'=> $fromUid])->value('nickname');
  243. $msgData['time_text'] = dateFormat($msgData['create_time']);
  244. //$this->sendMsg($frameId, ['success' => true, 'op' => 'push_live', 'scene'=> $scene, 'data' => $msgData, 'message' => '发送成功:' . $frameId]);
  245. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  246. $fids = array_values($fids);
  247. $fids = array_unique($fids);
  248. if($fids){
  249. foreach($fids as $fd){
  250. $this->sendMsg($fd, ['success' => true, 'op' => 'push_live' ,'scene'=> $scene, 'data' => $msgData, 'message' => '推送消息成功:' . $fd]);
  251. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$fd}-{$liveId}。");
  252. }
  253. }
  254. break;
  255. case 'login': // 登录
  256. $this->info("【{$scene} {$date}】Socket:登录成功【{$frameId}-{$fromUid}-{$op}】。");
  257. $this->sendMsg($frameId, ['success' => true,'op'=> $op, 'scene'=>$scene, 'message' => '登录成功', 'data' => $data, 't' => time()]);
  258. break;
  259. case 'live_entry': // 进入直播间消息
  260. case 'live_like': // 进入直播间消息
  261. case 'follow': // 关注主播消息
  262. case 'gift': // 打赏礼物消息
  263. $types = ['live_entry'=>'进入直播间消息','live_like'=>'点赞消息','follow'=>'关注消息','gift'=>'礼物消息'];
  264. $typeName = isset($types[$op])? $types[$op] : '直播间消息';
  265. $fids = RedisService::get("chats:bindFds:{$scene}_{$liveId}");
  266. $fids = array_values($fids);
  267. $fids = array_unique($fids);
  268. if($fids){
  269. foreach($fids as $fd){
  270. $this->sendMsg($fd, ['success' => true,'op'=> $op, 'scene'=>$scene, 'data' => $data, 'message' => $typeName, 't' => time()]);
  271. }
  272. }
  273. break;
  274. default:
  275. $this->sendMsg($frameId, ['success' => false, 'message' => 'ok', 'scene'=>$scene, 'data' => $data, 't' => time()]);
  276. break;
  277. }
  278. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理成功");
  279. } catch (\Exception $exception) {
  280. RedisService::set("caches:sockets:error_{$frameId}", ['error' => $exception->getMessage(),'trace'=>$exception->getTrace(), 'date' => $date], 7200);
  281. $this->info("【{$scene} {$date}】Socket:客户端【{$frameId}】消息处理错误 " . $exception->getMessage());
  282. }
  283. }
  284. /**
  285. * 签名验证
  286. * @param $data
  287. * @return bool
  288. */
  289. public function checkSign($data)
  290. {
  291. $checkSign = isset($data['sign']) ? $data['sign'] : '';
  292. $sign = getSign($data);
  293. if ($sign != $checkSign) {
  294. return false;
  295. }
  296. return true;
  297. }
  298. /**
  299. * 推送消息
  300. * @param $fd
  301. * @param $op
  302. * @param $data
  303. */
  304. public function sendMsg($fd, $data)
  305. {
  306. $date = date('Y-m-d H:i:s');
  307. try {
  308. if (!RedisService::exists("chats:frames:" . $fd)) {
  309. $this->info("【{$date}】Socket:客户端【{$fd}】推送用户已经掉线 ");
  310. return false;
  311. }
  312. $this->ws->push($fd, json_encode($data, 256));
  313. } catch (\Exception $exception) {
  314. $this->info("【{$date}】Socket:客户端【{$fd}】消息处理错误 " . $exception->getMessage());
  315. }
  316. }
  317. /**
  318. * 接收请求
  319. * @param $request
  320. * @param $response
  321. */
  322. public function request($request, $response)
  323. {
  324. }
  325. /**
  326. * 关闭连接
  327. * @param $ws
  328. * @param $fd
  329. */
  330. public function close($ws, $fd = '')
  331. {
  332. $date = date('Y-m-d H:i:s');
  333. RedisService::clear("chats:frames:" . $fd);
  334. $this->info("【{$date}】Socket:客户端【{$fd}】连接关闭");
  335. $this->ws->close($fd);
  336. }
  337. /**
  338. * 停止运行
  339. */
  340. public function stop()
  341. {
  342. // 直接杀
  343. $stoSh = base_path().'/crontab/socketStop.sh';
  344. if(file_exists($stoSh) && function_exists('exec')){
  345. exec("{$stoSh}");
  346. }
  347. echo "$stoSh\n";
  348. echo "socket stop success...\n";
  349. if ($this->ws) {
  350. $date = date('Y-m-d H:i:s');
  351. $this->info("【{$date}】Socket:停止运行服务");
  352. $this->ws->close();
  353. }
  354. }
  355. /**
  356. * 消息
  357. * @param string $data
  358. */
  359. public function info($data,$verbosity=true)
  360. {
  361. \logger()->channel('swoole')->info($data);
  362. if(env('SWOOLE_LOG', true) && $verbosity){
  363. parent::info($data);
  364. }
  365. }
  366. }