SocketServer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\ImChatModel;
  4. use App\Models\LiveChatModel;
  5. use App\Models\LiveModel;
  6. use App\Models\MessageModel;
  7. use App\Services\Api\ImChatService;
  8. use App\Services\Api\MemberService;
  9. use App\Services\Api\MessageService;
  10. use App\Services\ConfigService;
  11. use App\Services\LiveService;
  12. use App\Services\RedisService;
  13. use Illuminate\Console\Command;
  14. use Monolog\Logger;
  15. class SocketServer extends Command
  16. {
  17. public $ws;
  18. /**
  19. * The name and signature of the console command.
  20. *
  21. * @var string
  22. */
  23. protected $signature = 'swoole:socket {op?}';
  24. /**
  25. * The console command description.
  26. *
  27. * @var string
  28. */
  29. protected $description = 'Chat server run';
  30. protected $logger = null;
  31. /**
  32. * Create a new command instance.
  33. *
  34. * @return void
  35. */
  36. public function __construct()
  37. {
  38. parent::__construct();
  39. }
  40. /**
  41. * Execute the console command.
  42. *
  43. * @return mixed
  44. */
  45. public function handle()
  46. {
  47. $op = $this->argument('op');
  48. $op = $op ? $op : 'start';
  49. if ($op == 'start') {
  50. echo "swoole socket service start ...\n";
  51. $this->start();
  52. } else if ($op == 'stop') {
  53. echo "swoole socket service stop ...\n";
  54. $this->stop();
  55. }
  56. }
  57. /**
  58. * 运行
  59. */
  60. public function start()
  61. {
  62. try {
  63. //创建websocket服务器对象,监听0.0.0.0:7104端口
  64. $this->ws = new \Swoole\WebSocket\Server("0.0.0.0", env('SOCKET_PORT', '6630'));
  65. //监听WebSocket连接打开事件
  66. $this->ws->on('open', [$this, 'open']);
  67. //监听WebSocket消息事件
  68. $this->ws->on('message', [$this, 'message']);
  69. //监听WebSocket主动推送消息事件
  70. $this->ws->on('request', [$this, 'request']);
  71. //监听WebSocket连接关闭事件
  72. $this->ws->on('close', [$this, 'close']);
  73. $this->ws->start();
  74. } catch (\Exception $exception) {
  75. $date = date('Y-m-d H:i:s');
  76. RedisService::set("caches:sockets:error", $exception->getMessage(), 600);
  77. $this->info("【{$date}】Socket:运行异常=》" . $exception->getMessage());
  78. }
  79. }
  80. /**
  81. * 建立连接
  82. * @param $ws
  83. * @param $request
  84. */
  85. public function open($ws, $request)
  86. {
  87. $date = date('Y-m-d H:i:s');
  88. $this->ws->push($request->fd, json_encode(['success' => 'true', 'op' => 'conn', 'message' => '连接成功', 'fd' => $request->fd], 256));
  89. $this->info("【{$date}】Socket:客户端【{$request->fd}】连接成功");
  90. }
  91. /**
  92. * 接收消息
  93. * @param $ws
  94. * @param $frame
  95. */
  96. public function message($ws, $frame)
  97. {
  98. $date = date('Y-m-d H:i:s');
  99. RedisService::set("chats:frames:" . $frame->fd, json_decode($frame->data, true), 86400);
  100. if ($frame->data == 'ping') {
  101. $this->ws->push($frame->fd, 'pong');
  102. $this->info("【{$date}】Socket:客户端【{$frame->fd}】心跳包",false);
  103. return false;
  104. }
  105. // 消息处理
  106. $frameId = $frame->fd;
  107. $data = $frame->data ? json_decode($frame->data, true) : [];
  108. $fromUid = isset($data['from_user_id']) ? intval($data['from_user_id']) : 0;
  109. $op = isset($data['op']) ? $data['op'] : '';
  110. $scene = isset($data['scene']) && $data['scene'] ? $data['scene'] : 'chat';
  111. if (!in_array($op,['video_connect','video']) && !$this->checkSign($data)) {
  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_user_id']) ? intval($data['to_user_id']) : 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. 'form_user_name' => $fromUserName,
  168. 'to_user_name' => $toUserName,
  169. 'form_user_avatar' => $fromAvatar,
  170. 'to_user_avatar' => $toAvatar,
  171. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  172. 'content' => $msgType == 2 && $message ? get_image_path($message) : $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_image_url($msgData['content'], $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' => $op, 'scene'=> $scene, 'data' => $data, '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. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  217. $liveId = isset($data['live_id']) ? $data['live_id'] : 0;
  218. $message = isset($data['message']) ? trim($data['message']) : '';
  219. // 发送参数验证
  220. if ($toUid <= 0 || $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' => '参数错误']);
  223. return false;
  224. }
  225. $msgData = [
  226. 'from_user_id' => $fromUid,
  227. 'to_user_id' => $toUid,
  228. 'msg_type' => $msgType,
  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['time_text'] = dateFormat($msgData['create_time']);
  243. $this->sendMsg($frameId, ['success' => true, 'op' => $op, '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' ,'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. if ($this->ws) {
  324. $date = date('Y-m-d H:i:s');
  325. $this->info("【{$date}】Socket:停止运行服务");
  326. $this->ws->close();
  327. }
  328. }
  329. /**
  330. * 消息
  331. * @param string $data
  332. */
  333. public function info($data,$verbosity=true)
  334. {
  335. \logger()->channel('swoole')->info($data);
  336. if(env('SWOOLE_LOG', true) && $verbosity){
  337. parent::info($data);
  338. }
  339. }
  340. }