SocketServer.php 16 KB

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