SocketServer.php 16 KB

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