Handler.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LikeShop有特色的全开源社交分销电商系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 商业用途务必购买系统授权,以免引起不必要的法律纠纷
  7. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  8. // | 微信公众号:好象科技
  9. // | 访问官网:http://www.likemarket.net
  10. // | 访问社区:http://bbs.likemarket.net
  11. // | 访问手册:http://doc.likemarket.net
  12. // | 好象科技开发团队 版权所有 拥有最终解释权
  13. // +----------------------------------------------------------------------
  14. // | Author: LikeShopTeam-段誉
  15. // +----------------------------------------------------------------------
  16. namespace app\common\websocket;
  17. use Swoole\Server;
  18. use think\App;
  19. use think\Event;
  20. use think\facade\Log;
  21. use think\Request;
  22. use think\swoole\websocket\Room;
  23. use app\common\cache\ChatCache;
  24. use app\common\enum\ChatEnum;
  25. use app\common\enum\ChatMsgEnum;
  26. use Swoole\Websocket\Frame;
  27. use think\swoole\Websocket;
  28. class Handler extends Websocket
  29. {
  30. protected $server;
  31. protected $room;
  32. protected $parser;
  33. protected $cache;
  34. protected $prefix;
  35. public function __construct(App $app, Server $server, Room $room, Event $event, Parser $parser, ChatCache $redis)
  36. {
  37. try {
  38. $this->server = $server;
  39. $this->room = $room;
  40. $this->parser = $parser;
  41. $this->cache = $redis;
  42. $this->prefix = config('project.websocket_prefix');
  43. parent::__construct($app, $server, $room, $event);
  44. } catch (\Throwable $e) {
  45. Log::write('客服建立连接错误--'. $e->getMessage());
  46. }
  47. }
  48. public function onOpen($fd, Request $request)
  49. {
  50. $type = $request->get('type/s'); //登录类型,user kefu
  51. $token = $request->get('token/s');
  52. $terminal = $request->get('terminal/d');
  53. try {
  54. $user = $this->triggerEvent('login', [
  55. 'type' => $type,
  56. 'terminal' => $terminal,
  57. 'token' => $token
  58. ]);
  59. if ($user['code'] == 20001 || empty($user['data']['id'])) {
  60. throw new \Exception(empty($user['msg']) ? "未知错误" : $user['msg']);
  61. }
  62. } catch (\Throwable $e) {
  63. Log::write('onOpen失败--'. $e->getMessage());
  64. return $this->server->close($fd);
  65. }
  66. // 登录者绑定fd
  67. $this->bindFd($type, $user['data'], $fd);
  68. $this->ping($fd);
  69. return $this->pushData($fd, 'login', [
  70. 'msg' => '连接成功',
  71. 'msg_type' => ChatMsgEnum::TYPE_TEXT
  72. ]);
  73. }
  74. /**
  75. * @notes onMessage
  76. * @param Frame $frame
  77. * @return bool|mixed|void
  78. * @author 段誉
  79. * @date 2021/12/20 10:53
  80. */
  81. public function onMessage(Frame $frame)
  82. {
  83. $param = $this->parser->decode($frame->data);
  84. try {
  85. // 回应ping
  86. if ('ping' === $param['event']) {
  87. return $this->ping($frame->fd);
  88. }
  89. $param['handle'] = $this;
  90. $param['fd'] = $frame->fd;
  91. return $this->triggerEvent($param['event'], $param);
  92. } catch (\Throwable $e) {
  93. Log::write('onMessage错误--'. $e->getMessage());
  94. return $this->pushData($frame->fd, 'error', [
  95. 'msg' => $e->getMessage(),
  96. 'msg_type' => ChatMsgEnum::TYPE_TEXT
  97. ]);
  98. }
  99. }
  100. /**
  101. * @notes onClose
  102. * @param int $fd
  103. * @param int $reactorId
  104. * @author 段誉
  105. * @date 2021/12/15 19:03
  106. */
  107. public function onClose($fd, $reactorId)
  108. {
  109. $this->triggerEvent('close', ['handle' => $this, 'fd' => $fd]);
  110. $this->removeBind($fd);
  111. $this->server->close($fd);
  112. }
  113. /**
  114. * @notes 触发事件
  115. * @param string $event
  116. * @param array $data
  117. * @return mixed
  118. * @author 段誉
  119. * @date 2021/12/15 19:03
  120. */
  121. public function triggerEvent(string $event, array $data)
  122. {
  123. return $this->event->until('swoole.websocket.' . $event, $data);
  124. }
  125. /**
  126. * @notes 登录者的id绑定fd
  127. * @param $type
  128. * @param $user
  129. * @param $fd
  130. * @author 段誉
  131. * @date 2021/12/15 19:02
  132. */
  133. public function bindFd($type, $user, $fd)
  134. {
  135. $uid = $user['id'];
  136. // socket_fd_{fd} => ['uid' => {uid}, 'type' => {type}]
  137. // 以fd为键缓存当前fd的信息
  138. $fdKey = $this->prefix . 'fd_' . $fd;
  139. $fdData = [
  140. 'uid' => $uid,
  141. 'type' => $type,
  142. 'nickname' => $user['nickname'],
  143. 'avatar' => $user['avatar'],
  144. 'terminal' => $user['terminal'],
  145. 'token' => $user['token'],
  146. ];
  147. $this->cache->set($fdKey, json_encode($fdData, true));
  148. // socket_user_1(user_id) => {fd} 用户user_id为1 的 fd
  149. // socket_kefu_2(kefu_id) => {fd} 客服kefu_id为2 的 fd
  150. $uidKey = $this->prefix . $type . '_' . $uid;
  151. $this->cache->sadd($uidKey, $fd);
  152. // socket_user => {fd} 在线用户的所有fd
  153. if ($type == 'kefu') {
  154. $groupKey = $this->prefix . 'kefu';
  155. } else {
  156. $groupKey = $this->prefix . 'user';
  157. }
  158. $this->cache->sadd($groupKey, $uid);
  159. }
  160. /**
  161. * @notes 移除绑定
  162. * @param $fd
  163. * @author 段誉
  164. * @date 2021/12/15 19:02
  165. */
  166. public function removeBind($fd)
  167. {
  168. $data = $this->getDataByFd($fd);
  169. if ($data) {
  170. $key = $this->prefix . 'user';
  171. if ($data['type'] == ChatEnum::TYPE_KEFU) {
  172. $key = $this->prefix . 'kefu';
  173. }
  174. $this->cache->srem($key, $data['uid']); // socket_user => 11
  175. $this->cache->srem($key . '_' . $data['uid'], $fd); // socket_user_uid => fd
  176. }
  177. $this->cache->del($this->prefix . 'fd_' . $fd);
  178. }
  179. /**
  180. * @notes 通过登录id和登录类型获取对应的fd
  181. * @param $uid
  182. * @param $type
  183. * @return bool
  184. * @author 段誉
  185. * @date 2021/12/15 19:02
  186. */
  187. public function getFdByUid($uid, $type)
  188. {
  189. $key = $this->prefix . $type . '_' . $uid;
  190. return $this->cache->sMembers($key);
  191. }
  192. /**
  193. * @notes 根据fd获取登录的id和登录类型
  194. * @param $fd
  195. * @return mixed|string
  196. * @author 段誉
  197. * @date 2021/12/15 19:02
  198. */
  199. public function getDataByFd($fd)
  200. {
  201. $key = $this->prefix . 'fd_' . $fd;
  202. $result = $this->cache->get($key);
  203. if (!empty($result)) {
  204. $result = json_decode($result, true);
  205. }
  206. return $result;
  207. }
  208. /**
  209. * @notes ping
  210. * @param $fd
  211. * @return bool
  212. * @author 段誉
  213. * @date 2021/12/20 15:19
  214. */
  215. public function ping($fd)
  216. {
  217. $data = $this->getDataByFd($fd);
  218. if (!empty($data)) {
  219. return $this->pushData($fd, 'ping', ['terminal_time' => time()]);
  220. }
  221. return true;
  222. }
  223. /**
  224. * @notes 推送数据
  225. * @param $fd
  226. * @param $event
  227. * @param $data
  228. * @return bool
  229. * @author 段誉
  230. * @date 2021/12/15 19:02
  231. */
  232. public function pushData($fd, $event, $data)
  233. {
  234. $data = $this->parser->encode($event, $data);
  235. // fd非数组时转为数组
  236. if (!is_array($fd)) {
  237. $fd = [$fd];
  238. }
  239. // 向fd发送消息
  240. foreach ($fd as $item) {
  241. if ($this->server->exist($item)) {
  242. $this->server->push($item, $data);
  243. }
  244. }
  245. return true;
  246. }
  247. /**
  248. * @notes 在线fd
  249. * @param $fd
  250. * @return array
  251. * @author 段誉
  252. * @date 2021/12/17 18:19
  253. */
  254. public function onlineFd($fd)
  255. {
  256. $result = [];
  257. if (empty($fd)) {
  258. return $result;
  259. }
  260. if (!is_array($fd)) {
  261. $fd = [$fd];
  262. }
  263. foreach ($fd as $item) {
  264. if ($this->server->exist($item)) {
  265. $result[] = $item;
  266. }
  267. }
  268. return $result;
  269. }
  270. }