SocketServer.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\ImChatModel;
  4. use App\Services\Api\ImChatService;
  5. use App\Services\Api\MemberService;
  6. use App\Services\Api\MessageService;
  7. use App\Services\ConfigService;
  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 = 'websocket 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', '6620'));
  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_user_id']) ? intval($data['from_user_id']) : 0;
  105. $op = isset($data['op']) ? $data['op'] : '';
  106. //$this->sendMsg($frame->fd, $data);
  107. if (!in_array($op,['video_connect','video']) && !$this->checkSign($data)) {
  108. $this->info("【{$date}】Socket:签名失败【{$frameId}-{$fromUid}】");
  109. return false;
  110. }
  111. $uuid = isset($data['uuid']) ? $data['uuid'] : uniqid();
  112. $toUid = isset($data['to_user_id']) ? intval($data['to_user_id']) : 0;
  113. $apiUrl = isset($data['api_url']) ? trim($data['api_url']) : '';
  114. $chatKey = isset($data['chat_key']) ? trim($data['chat_key']) : '';
  115. $chatKey = $chatKey ? $chatKey : getChatKey($fromUid, $toUid);
  116. try {
  117. // 推送Fd处理
  118. if ($fromUid && $frameId) {
  119. $fds = RedisService::get("chats:bindFds:{$chatKey}");
  120. $fds = $fds? $fds : [];
  121. $fds[$op.'_'.$fromUid] = $frameId;
  122. RedisService::set("chats:bindFds:{$chatKey}", $fds, 86400);
  123. RedisService::set("chats:bind:{$fromUid}", ['fd' => $frameId, 'user_id' => $fromUid, 'uuid' => $uuid, 'chat_key' => $chatKey], 86400);
  124. }
  125. switch ($op) {
  126. case 'chat': // 文字聊天
  127. $msgType = isset($data['msg_type']) ? $data['msg_type'] : 1;
  128. $message = isset($data['message']) ? trim($data['message']) : '';
  129. // 验证是否还有次数和付费提示 (客服不限制)
  130. if (!$check = ImChatService::make()->checkChat($fromUid, $toUid, 1)) {
  131. $config = ConfigService::make()->getConfigByCode('chat_buy_num_money');
  132. $config = $config ? explode('/', $config) : [];
  133. $money = isset($config[0]) && $config[0] > 0 ? $config[0] : 10;
  134. $num = isset($config[1]) && $config[1] > 0 ? $config[1] : 10;
  135. $tips = "抱歉您的免费次数已经用完,请先余额支付【{$money}元】购买【{$num}次】聊天次数再使用聊天服务。";
  136. $this->info("【{$date}】Socket:次数不足【{$frameId}-{$fromUid}】。");
  137. $this->sendMsg($frameId, ['success' => true, 'op' => 'buy', 'data' => ['type' => 1, 'tips' => $tips], 'message' => '次数不足,需要付费']);
  138. return false;
  139. }
  140. // 发送参数验证
  141. $message = MessageService::make()->filterMessage($message, 1);
  142. if ($toUid <= 0 || $fromUid <= 0 || empty($message)) {
  143. $this->info("【{$date}】Socket:参数错误,from@{$fromUid}-to@{$toUid}。");
  144. $this->sendMsg($frameId, ['success' => false, 'message' => '参数错误']);
  145. return false;
  146. }
  147. $data = [
  148. 'from_user_id' => $fromUid,
  149. 'to_user_id' => $toUid,
  150. 'msg_type' => $msgType,
  151. 'description' => $msgType == 1 ? mb_substr($message, 0, 20) : '',
  152. 'message' => $msgType != 1 && $message ? get_image_path($message) : $message,
  153. 'chat_key' => $chatKey,
  154. 'create_time' => time(),
  155. 'update_time' => time(),
  156. 'is_read' => 2,
  157. 'from_is_show' => 1,
  158. 'to_is_show' => 1,
  159. 'status' => 1
  160. ];
  161. if (!$id = ImChatModel::insertGetId($data)) {
  162. $data = ['success' => false, 'message' => '消息发送失败'];
  163. $this->sendMsg($frameId, $data);
  164. return false;
  165. }
  166. // 推送消息给对方
  167. $toInfo = MemberService::make()->getChatInfo($toUid, '', $apiUrl);
  168. $fromInfo = MemberService::make()->getChatInfo($fromUid, '', $apiUrl);
  169. $data['from_nickname'] = isset($fromInfo['nickname']) ? $fromInfo['nickname'] : '';
  170. $data['from_avatar'] = isset($fromInfo['avatar']) ? $fromInfo['avatar'] : '';
  171. $data['to_nickname'] = isset($toInfo['nickname']) ? $toInfo['nickname'] : '';
  172. $data['to_avatar'] = isset($toInfo['avatar']) ? $toInfo['avatar'] : '';
  173. $data['time_text'] = dateFormat($data['create_time']);
  174. $this->sendMsg($frameId, ['success' => true, 'op' => $op, 'data' => $data, 'message' => '发送成功:' . $frameId]);
  175. $toBindData = RedisService::get("chats:bind:{$toUid}");
  176. $toFd = isset($toBindData['fd']) ? $toBindData['fd'] : 0;
  177. if ($toBindData && $toFd) {
  178. $this->sendMsg($toFd, ['success' => true, 'op' => $op, 'data' => $data, 'message' => '推送消息成功:' . $toFd]);
  179. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】推送消息给【{$toFd}-{$toUid}。");
  180. }
  181. // 更新消费的次数
  182. ImChatService::make()->updateChatParams($fromUid, $toUid, 1, 1);
  183. break;
  184. case 'video_connect': // 视频通话连接
  185. // 推送消息给对方
  186. $toInfo = MemberService::make()->getChatInfo($toUid, '', $apiUrl);
  187. $fromInfo = MemberService::make()->getChatInfo($fromUid, '', $apiUrl);
  188. $data['from_nickname'] = isset($fromInfo['nickname']) ? $fromInfo['nickname'] : '';
  189. $data['from_avatar'] = isset($fromInfo['avatar']) ? $fromInfo['avatar'] : '';
  190. $data['to_nickname'] = isset($toInfo['nickname']) ? $toInfo['nickname'] : '';
  191. $data['to_avatar'] = isset($toInfo['avatar']) ? $toInfo['avatar'] : '';
  192. $data['time_text'] = dateFormat(time());
  193. // 推送消息
  194. $fds = RedisService::get("chats:bindFds:{$chatKey}");
  195. $toFds = RedisService::get("chats:bindFds:0_{$toUid}");
  196. $toFds = $toFds? array_values($toFds) : [];
  197. $fds = $fds? array_values($fds) : [];
  198. $fds = $toFds? array_merge($toFds, $fds) : $fds;
  199. $this->sendMsg($frameId, ['success' => true, 'op' => $op, 'data' => $data, 'message' => '发送成功:' . $frameId]);
  200. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】@{$data['message']},消息群推给,".json_encode($fds));
  201. if ($fds) {
  202. $fds = array_unique($fds);
  203. foreach($fds as $toFd){
  204. if($toFd != $frameId){
  205. $this->sendMsg($toFd, ['success' => true, 'op' => $op, 'data' => $data, 'message' => '推送视频通话消息成功:' . $toFd.'-'.$frameId]);
  206. $this->info("【{$date}】Socket:客户端【{$toFd}】@{$data['message']},推送视频消息,来源【{$frameId}】");
  207. }
  208. }
  209. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】@{$data['message']},群推结束");
  210. }
  211. break;
  212. case 'video': // 视频/语音聊天结束
  213. // 发送参数验证
  214. $type = isset($data['type']) ? intval($data['type']) : 1;
  215. $status = isset($data['status']) ? intval($data['status']) : 2;
  216. $videoTime = isset($data['video_time']) ? intval($data['video_time']) : 0;
  217. $message = isset($data['message']) && $data['message'] ? trim($data['message']) : '通话结束';
  218. if ($toUid <= 0 || $fromUid <= 0 || empty($message) || $status <= 0) {
  219. $this->sendMsg($frameId, ['success' => false, 'message' => '参数错误']);
  220. return false;
  221. }
  222. $data = [
  223. 'from_user_id' => $fromUid,
  224. 'to_user_id' => $toUid,
  225. 'msg_type' => 5,
  226. 'description' => $message,
  227. 'message' => $message,
  228. 'chat_key' => $chatKey,
  229. 'create_time' => time(),
  230. 'update_time' => time(),
  231. 'is_read' => 2,
  232. 'from_is_show' => 1,
  233. 'to_is_show' => 1,
  234. 'is_connect' => $status, // 1-接通,2-拒绝,3-取消
  235. 'video_time' => $videoTime, // 通话时长
  236. 'status' => 1
  237. ];
  238. if($type == 2){
  239. $data['from_user_id'] = $toUid;
  240. $data['to_user_id'] = $fromUid;
  241. }
  242. if (!$id = ImChatModel::insertGetId($data)) {
  243. $data = ['success' => false, 'message' => '视频消息发送失败'];
  244. $this->sendMsg($frameId, $data);
  245. return false;
  246. }
  247. // 推送消息给对方
  248. $toInfo = MemberService::make()->getChatInfo($data['to_user_id'], '', $apiUrl);
  249. $fromInfo = MemberService::make()->getChatInfo($data['from_user_id'], '', $apiUrl);
  250. $data['from_nickname'] = isset($fromInfo['nickname']) ? $fromInfo['nickname'] : '';
  251. $data['from_avatar'] = isset($fromInfo['avatar']) ? $fromInfo['avatar'] : '';
  252. $data['to_nickname'] = isset($toInfo['nickname']) ? $toInfo['nickname'] : '';
  253. $data['to_avatar'] = isset($toInfo['avatar']) ? $toInfo['avatar'] : '';
  254. $data['time_text'] = dateFormat($data['create_time']);
  255. $str = [];
  256. if($videoTime>3600){
  257. $hour = intval($videoTime/3600);
  258. $str[] = $hour<10?'0'.$hour:$hour;
  259. }
  260. if($videoTime%3600 > 0){
  261. $minute = intval($videoTime%3600/60);
  262. $str[] = $minute<10?'0'.$minute:$minute;
  263. }
  264. if($videoTime%60 > 0){
  265. $second = intval($videoTime%60);
  266. $str[] = $second<10?'0'.$second:$second;
  267. }
  268. $data['video_time_text'] = $str? implode(':', $str) : '';
  269. // 推送消息
  270. $fds = RedisService::get("chats:bindFds:{$chatKey}");
  271. $fromFds = RedisService::get("chats:bindFds:0_{$fromUid}");
  272. $toFds = RedisService::get("chats:bindFds:0_{$toUid}");
  273. $fromFds = $fromFds? array_values($fromFds) : [];
  274. $toFds = $toFds? array_values($toFds) : [];
  275. $fds = $fds? array_values($fds) : [];
  276. $fds = $fromFds? array_merge($fromFds, $fds) : $fds;
  277. $fds = $toFds? array_merge($toFds, $fds) : $fds;
  278. $this->sendMsg($frameId, ['success' => true, 'op' => $op, 'data' => $data, 'message' => '发送成功:' . $frameId]);
  279. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】@{$data['message']},消息群推给,".json_encode($fds));
  280. if ($fds) {
  281. $fds = array_unique($fds);
  282. foreach($fds as $toFd){
  283. if($toFd != $frameId || $type == 2){
  284. $this->sendMsg($toFd, ['success' => true, 'op' => $op, 'data' => $data, 'message' => '推送视频通话消息成功:' . $toFd.'-来源'.$frameId]);
  285. $this->info("【{$date}】Socket:客户端【{$toFd}】@{$data['message']},推送视频消息,来源【{$frameId}】");
  286. }
  287. }
  288. $this->info("【{$date}】Socket:客户端【{$frameId}-{$fromUid}】@{$data['message']},消息群推结束");
  289. }
  290. // 如果通话时长
  291. if ($status == 1 && $videoTime > 0) {
  292. // 更新剩余时长
  293. if($type == 2){
  294. ImChatService::make()->updateChatParams($toUid, $fromUid, $videoTime, 2);
  295. }else{
  296. ImChatService::make()->updateChatParams($fromUid, $toUid, $videoTime, 2);
  297. }
  298. }
  299. break;
  300. case 'video-login': // 登录
  301. case 'login': // 登录
  302. $this->info("【{$date}】Socket:登录成功【{$frameId}-{$fromUid}-{$op}】。");
  303. $this->sendMsg($frameId, ['success' => true,'op'=> $op, 'message' => '登录成功', 'data' => $data, 't' => time()]);
  304. break;
  305. default:
  306. $this->sendMsg($frameId, ['success' => false, 'message' => 'ok', 'data' => $data, 't' => time()]);
  307. break;
  308. }
  309. $this->info("【{$date}】Socket:客户端【{$frameId}】消息处理成功");
  310. } catch (\Exception $exception) {
  311. RedisService::set("caches:sockets:error_{$frameId}", ['error' => $exception->getTrace(), 'date' => $date], 7200);
  312. $this->info("【{$date}】Socket:客户端【{$frameId}】消息处理错误 " . $exception->getMessage());
  313. }
  314. }
  315. /**
  316. * 签名验证
  317. * @param $data
  318. * @return bool
  319. */
  320. public function checkSign($data)
  321. {
  322. $checkSign = isset($data['sign']) ? $data['sign'] : '';
  323. $sign = getSign($data);
  324. if ($sign != $checkSign) {
  325. return false;
  326. }
  327. return true;
  328. }
  329. /**
  330. * 推送消息
  331. * @param $fd
  332. * @param $op
  333. * @param $data
  334. */
  335. public function sendMsg($fd, $data)
  336. {
  337. $date = date('Y-m-d H:i:s');
  338. try {
  339. if (!RedisService::exists("chats:frames:" . $fd)) {
  340. $this->info("【{$date}】Socket:客户端【{$fd}】推送用户已经掉线 ");
  341. return false;
  342. }
  343. $this->ws->push($fd, json_encode($data, 256));
  344. } catch (\Exception $exception) {
  345. $this->info("【{$date}】Socket:客户端【{$fd}】消息处理错误 " . $exception->getMessage());
  346. }
  347. }
  348. /**
  349. * 接收请求
  350. * @param $request
  351. * @param $response
  352. */
  353. public function request($request, $response)
  354. {
  355. }
  356. /**
  357. * 关闭连接
  358. * @param $ws
  359. * @param $fd
  360. */
  361. public function close($ws, $fd = '')
  362. {
  363. $date = date('Y-m-d H:i:s');
  364. RedisService::clear("chats:frames:" . $fd);
  365. $this->info("【{$date}】Socket:客户端【{$fd}】连接关闭");
  366. $this->ws->close($fd);
  367. }
  368. /**
  369. * 停止运行
  370. */
  371. public function stop()
  372. {
  373. if ($this->ws) {
  374. $date = date('Y-m-d H:i:s');
  375. $this->info("【{$date}】Socket:停止运行服务");
  376. $this->ws->close();
  377. }
  378. }
  379. /**
  380. * 消息
  381. * @param string $data
  382. */
  383. public function info($data,$verbosity=true)
  384. {
  385. \logger()->channel('swoole')->info($data);
  386. if(env('SWOOLE_LOG', true) && $verbosity){
  387. parent::info($data);
  388. }
  389. }
  390. }