Manager.php 6.1 KB

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