Websocket.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. namespace think\swoole;
  3. use Swoole\Server;
  4. use Swoole\WebSocket\Frame;
  5. use think\Event;
  6. use think\Request;
  7. use think\swoole\websocket\Pusher;
  8. use think\swoole\websocket\Room;
  9. /**
  10. * Class Websocket
  11. */
  12. class Websocket
  13. {
  14. /**
  15. * @var \think\App
  16. */
  17. protected $app;
  18. /**
  19. * @var Server
  20. */
  21. protected $server;
  22. /**
  23. * @var Room
  24. */
  25. protected $room;
  26. /**
  27. * Scoket sender's fd.
  28. *
  29. * @var integer
  30. */
  31. protected $sender;
  32. /**
  33. * Recepient's fd or room name.
  34. *
  35. * @var array
  36. */
  37. protected $to = [];
  38. /**
  39. * Determine if to broadcast.
  40. *
  41. * @var boolean
  42. */
  43. protected $isBroadcast = false;
  44. /** @var Event */
  45. protected $event;
  46. /**
  47. * Websocket constructor.
  48. *
  49. * @param \think\App $app
  50. * @param Server $server
  51. * @param Room $room
  52. * @param Event $event
  53. */
  54. public function __construct(\think\App $app, Server $server, Room $room, Event $event)
  55. {
  56. $this->app = $app;
  57. $this->server = $server;
  58. $this->room = $room;
  59. $this->event = $event;
  60. }
  61. /**
  62. * "onOpen" listener.
  63. *
  64. * @param int $fd
  65. * @param Request $request
  66. */
  67. public function onOpen($fd, Request $request)
  68. {
  69. $this->event->trigger('swoole.websocket.Open', $request);
  70. }
  71. /**
  72. * "onMessage" listener.
  73. *
  74. * @param Frame $frame
  75. */
  76. public function onMessage(Frame $frame)
  77. {
  78. $this->event->trigger('swoole.websocket.Message', $frame);
  79. $this->event->trigger('swoole.websocket.Event', $this->decode($frame->data));
  80. }
  81. /**
  82. * "onClose" listener.
  83. *
  84. * @param int $fd
  85. * @param int $reactorId
  86. */
  87. public function onClose($fd, $reactorId)
  88. {
  89. $this->event->trigger('swoole.websocket.Close', $reactorId);
  90. }
  91. /**
  92. * Set broadcast to true.
  93. */
  94. public function broadcast(): self
  95. {
  96. $this->isBroadcast = true;
  97. return $this;
  98. }
  99. /**
  100. * Get broadcast status value.
  101. */
  102. public function isBroadcast()
  103. {
  104. return $this->isBroadcast;
  105. }
  106. /**
  107. * Set multiple recipients fd or room names.
  108. *
  109. * @param integer|string|array
  110. *
  111. * @return $this
  112. */
  113. public function to($values): self
  114. {
  115. $values = is_string($values) || is_int($values) ? func_get_args() : $values;
  116. foreach ($values as $value) {
  117. if (!in_array($value, $this->to)) {
  118. $this->to[] = $value;
  119. }
  120. }
  121. return $this;
  122. }
  123. /**
  124. * Get push destinations (fd or room name).
  125. */
  126. public function getTo()
  127. {
  128. return $this->to;
  129. }
  130. /**
  131. * Join sender to multiple rooms.
  132. *
  133. * @param string|integer|array $rooms
  134. *
  135. * @return $this
  136. */
  137. public function join($rooms): self
  138. {
  139. $rooms = is_string($rooms) || is_int($rooms) ? func_get_args() : $rooms;
  140. $this->room->add($this->getSender(), $rooms);
  141. return $this;
  142. }
  143. /**
  144. * Make sender leave multiple rooms.
  145. *
  146. * @param array|string|integer $rooms
  147. *
  148. * @return $this
  149. */
  150. public function leave($rooms = []): self
  151. {
  152. $rooms = is_string($rooms) || is_int($rooms) ? func_get_args() : $rooms;
  153. $this->room->delete($this->getSender(), $rooms);
  154. return $this;
  155. }
  156. public function push($data)
  157. {
  158. $fds = $this->getFds();
  159. $assigned = !empty($this->getTo());
  160. try {
  161. if (empty($fds) && $assigned) {
  162. return false;
  163. }
  164. $job = new Job([Pusher::class, 'push'], [
  165. 'sender' => $this->getSender() ?: 0,
  166. 'descriptors' => $fds,
  167. 'broadcast' => $this->isBroadcast(),
  168. 'assigned' => $assigned,
  169. 'payload' => $data,
  170. ]);
  171. if ($this->server->taskworker) {
  172. $result = $job->run($this->app);
  173. } else {
  174. $result = $this->server->task($job);
  175. }
  176. return $result !== false;
  177. } finally {
  178. $this->reset();
  179. }
  180. }
  181. public function emit(string $event, ...$data): bool
  182. {
  183. return $this->push($this->encode([
  184. 'type' => $event,
  185. 'data' => $data,
  186. ]));
  187. }
  188. protected function encode($packet)
  189. {
  190. return json_encode($packet);
  191. }
  192. protected function decode($payload)
  193. {
  194. $data = json_decode($payload, true);
  195. return [
  196. 'type' => $data['type'] ?? null,
  197. 'data' => $data['data'] ?? null,
  198. ];
  199. }
  200. /**
  201. * Close current connection.
  202. *
  203. * @param int|null $fd
  204. * @return boolean
  205. */
  206. public function close(int $fd = null)
  207. {
  208. return $this->server->close($fd ?: $this->getSender());
  209. }
  210. /**
  211. * @param int|null $fd
  212. * @return bool
  213. */
  214. public function isEstablished(int $fd = null): bool
  215. {
  216. return $this->server->isEstablished($fd ?: $this->getSender());
  217. }
  218. /**
  219. * @param int|null $fd
  220. * @param int $code
  221. * @param string $reason
  222. * @return bool
  223. */
  224. public function disconnect(int $fd = null, int $code = 1000, string $reason = ''): bool
  225. {
  226. return $this->server->disconnect($fd ?: $this->getSender(), $code, $reason);
  227. }
  228. /**
  229. * Set sender fd.
  230. *
  231. * @param integer
  232. *
  233. * @return $this
  234. */
  235. public function setSender(int $fd)
  236. {
  237. $this->sender = $fd;
  238. $this->reset();
  239. return $this;
  240. }
  241. /**
  242. * Get current sender fd.
  243. */
  244. public function getSender()
  245. {
  246. return $this->sender;
  247. }
  248. /**
  249. * Get all fds we're going to push data to.
  250. */
  251. protected function getFds()
  252. {
  253. $to = $this->getTo();
  254. $fds = array_filter($to, function ($value) {
  255. return is_int($value);
  256. });
  257. $rooms = array_diff($to, $fds);
  258. foreach ($rooms as $room) {
  259. $clients = $this->room->getClients($room);
  260. // fallback fd with wrong type back to fds array
  261. if (empty($clients) && is_numeric($room)) {
  262. $fds[] = $room;
  263. } else {
  264. $fds = array_merge($fds, $clients);
  265. }
  266. }
  267. return array_values(array_unique($fds));
  268. }
  269. protected function reset()
  270. {
  271. $this->isBroadcast = false;
  272. $this->to = [];
  273. }
  274. }