SocketServer.php 16 KB

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