Manager.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\webscoket;
  12. use app\webscoket\handler\AdminHandler;
  13. use app\webscoket\handler\MerchantHandler;
  14. use app\webscoket\handler\UserHandler;
  15. use Swoole\Server;
  16. use Swoole\Table as SwooleTable;
  17. use Swoole\Websocket\Frame;
  18. use think\Config;
  19. use think\Event;
  20. use think\facade\Cache;
  21. use think\Request;
  22. use think\response\Json;
  23. use think\swoole\Table;
  24. use think\swoole\Websocket;
  25. use think\swoole\websocket\Room;
  26. /**
  27. * Class Manager
  28. * @package app\webscoket
  29. * @author xaboy
  30. * @day 2020-04-29
  31. */
  32. class Manager extends Websocket
  33. {
  34. /**
  35. * @var \Swoole\WebSocket\Server
  36. */
  37. protected $server;
  38. /**
  39. * @var Ping
  40. */
  41. protected $pingService;
  42. /**
  43. * @var int
  44. */
  45. protected $cache_timeout;
  46. const USER_TYPE = ['admin', 'user', 'mer'];
  47. /**
  48. * Manager constructor.
  49. * @param Server $server
  50. * @param Room $room
  51. * @param Event $event
  52. * @param Ping $ping
  53. * @param Config $config
  54. */
  55. public function __construct(Server $server, Room $room, Event $event, Ping $ping, Config $config)
  56. {
  57. parent::__construct($server, $room, $event);
  58. $this->pingService = $ping;
  59. $this->cache_timeout = (int)($config->get('swoole.websocket.ping_timeout', 60000) / 1000) + 2;
  60. app()->bind('websocket_handler_admin', AdminHandler::class);
  61. app()->bind('websocket_handler_user', UserHandler::class);
  62. app()->bind('websocket_handler_mer', MerchantHandler::class);
  63. }
  64. /**
  65. * @param int $fd
  66. * @param Request $request
  67. * @return mixed
  68. * @author xaboy
  69. * @day 2020-05-06
  70. */
  71. public function onOpen($fd, Request $request)
  72. {
  73. $type = $request->get('type');
  74. $token = $request->get('token');
  75. if (!$token || !in_array($type, self::USER_TYPE)) {
  76. return $this->server->close($fd);
  77. }
  78. try {
  79. $data = $this->exec($type, 'login', compact('fd', 'request', 'token'))->getData();
  80. } catch (\Exception $e) {
  81. return $this->server->close($fd);
  82. }
  83. if (!isset($data['status']) || $data['status'] != 200 || !($data['data']['uid'] ?? null))
  84. return $this->server->close($fd);
  85. $uid = $data['data']['uid'];
  86. $type = array_search($type, self::USER_TYPE);
  87. $this->login($type, $uid, $fd, $data['data']['data']['mer_id'] ?? null);
  88. $this->getTable()->set($fd, compact('type', 'uid', 'fd'));
  89. $this->pingService->createPing($fd, time(), $this->cache_timeout);
  90. return $this->send($fd, app('json')->message('ping', ['now' => time()]));
  91. }
  92. public function login($type, $uid, $fd, $merId)
  93. {
  94. $key = '_ws_' . $type;
  95. Cache::sadd($key, $fd);
  96. Cache::sadd($key . $uid, $fd);
  97. if ($merId) {
  98. $this->merLogin($uid, $fd, $merId);
  99. }
  100. $this->refresh($type, $uid);
  101. }
  102. public function merLogin($uid, $fd, $merId)
  103. {
  104. Cache::sadd('_wsm_0' . $merId, $fd);
  105. Cache::set('_wsm_1' . $uid, $merId);
  106. $this->refreshMer($uid, $merId);
  107. }
  108. public function refreshMer($uid, $merId)
  109. {
  110. Cache::expire('_wsm_0' . $merId, 1800);
  111. Cache::expire('_wsm_1' . $uid, 1800);
  112. }
  113. public function refresh($type, $uid)
  114. {
  115. $key = '_ws_' . $type;
  116. Cache::expire($key, 1800);
  117. Cache::expire($key . $uid, 1800);
  118. }
  119. public function logout($type, $uid, $fd)
  120. {
  121. $key = '_ws_' . $type;
  122. Cache::srem($key, $fd);
  123. Cache::srem($key . $uid, $fd);
  124. $merId = Cache::get('_wsm_1' . $uid);
  125. if ($merId) {
  126. Cache::delete('_wsm_1' . $uid);
  127. Cache::srem('_wsm_0' . $merId, $fd);
  128. }
  129. }
  130. public static function merFd($merId)
  131. {
  132. return Cache::smembers('_wsm_0' . $merId) ?: [];
  133. }
  134. public static function userFd($type, $uid = '')
  135. {
  136. $key = '_ws_' . $type . $uid;
  137. return Cache::smembers($key) ?: [];
  138. }
  139. /**
  140. * @return SwooleTable
  141. * @author xaboy
  142. * @day 2020-05-06
  143. */
  144. protected function getTable()
  145. {
  146. return app()->make(Table::class)->get('user');
  147. }
  148. /**
  149. * @param $type
  150. * @param $method
  151. * @param $result
  152. * @return null|Json
  153. * @author xaboy
  154. * @day 2020-05-06
  155. */
  156. protected function exec($type, $method, $result)
  157. {
  158. $handler = app()->make('websocket_handler_' . $type);
  159. if (!method_exists($handler, $method)) return null;
  160. /** @var Json $response */
  161. return $handler->{$method}($result);
  162. }
  163. /**
  164. * @param Frame $frame
  165. * @return bool
  166. * @author xaboy
  167. * @day 2020-04-29
  168. */
  169. public function onMessage(Frame $frame)
  170. {
  171. $info = $this->getTable()->get($frame->fd);
  172. $result = json_decode($frame->data, true) ?: [];
  173. if (!isset($result['type']) || !$result['type']) return true;
  174. $this->refresh($info['type'], $info['uid']);
  175. if ($result['type'] == 'ping') {
  176. return $this->send($frame->fd, app('json')->message('ping', ['now' => time()]));
  177. }
  178. $data = $result['data'] ?? [];
  179. $frame->uid = $info['uid'];
  180. /** @var Json $response */
  181. $response = $this->exec(self::USER_TYPE[$info['type']], $result['type'], compact('data', 'frame'));
  182. if ($response) return $this->send($frame->fd, $response);
  183. return true;
  184. }
  185. protected function send($fd, Json $json)
  186. {
  187. $this->pingService->createPing($fd, time(), $this->cache_timeout);
  188. if ($this->server->isEstablished($fd) && $this->server->exist($fd)) {
  189. $this->server->push($fd, json_encode($json->getData()));
  190. }
  191. return true;
  192. }
  193. /**
  194. * @param int $fd
  195. * @param int $reactorId
  196. * @author xaboy
  197. * @day 2020-04-29
  198. */
  199. public function onClose($fd, $reactorId)
  200. {
  201. // var_dump('onClose');
  202. if ($this->getTable()->exist($fd)) {
  203. $data = $this->getTable()->get($fd);
  204. $this->logout($data['type'], $data['uid'], $fd);
  205. $this->getTable()->del($fd);
  206. $this->exec(self::USER_TYPE[$data['type']], 'close', $data);
  207. }
  208. $this->pingService->removePing($fd);
  209. }
  210. }