Manager.php 6.1 KB

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