Socket.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  2. namespace PHPSocketIO;
  3. use Closure;
  4. use Exception;
  5. use PHPSocketIO\Event\Emitter;
  6. use PHPSocketIO\Parser\Parser;
  7. class Socket extends Emitter
  8. {
  9. public $nsp = null;
  10. public $server = null;
  11. public $adapter = null;
  12. public $id = null;
  13. public $path = '/';
  14. public $request = null;
  15. public $client = null;
  16. public $conn = null;
  17. public $rooms = [];
  18. public $_rooms = [];
  19. public $flags = [];
  20. public $acks = [];
  21. public $connected = true;
  22. public $disconnected = false;
  23. public $handshake = [];
  24. public $userId = null;
  25. public $isGuest = false;
  26. public static $events = [
  27. 'error' => 'error',
  28. 'connect' => 'connect',
  29. 'disconnect' => 'disconnect',
  30. 'newListener' => 'newListener',
  31. 'removeListener' => 'removeListener'
  32. ];
  33. public static $flagsMap = [
  34. 'json' => 'json',
  35. 'volatile' => 'volatile',
  36. 'broadcast' => 'broadcast'
  37. ];
  38. public function __construct($nsp, $client)
  39. {
  40. $this->nsp = $nsp;
  41. $this->server = $nsp->server;
  42. $this->adapter = $this->nsp->adapter;
  43. $this->id = ($nsp->name !== '/') ? $nsp->name . '#' . $client->id : $client->id;
  44. $this->request = $client->request;
  45. $this->client = $client;
  46. $this->conn = $client->conn;
  47. $this->handshake = $this->buildHandshake();
  48. Debug::debug('IO Socket __construct');
  49. }
  50. public function __destruct()
  51. {
  52. Debug::debug('IO Socket __destruct');
  53. }
  54. public function buildHandshake(): array
  55. {
  56. //todo check this->request->_query
  57. $info = ! empty($this->request->url) ? parse_url($this->request->url) : [];
  58. $query = [];
  59. if (isset($info['query'])) {
  60. parse_str($info['query'], $query);
  61. }
  62. return [
  63. 'headers' => $this->request->headers ?? [],
  64. 'time' => date('D M d Y H:i:s') . ' GMT',
  65. 'address' => $this->conn->remoteAddress,
  66. 'xdomain' => isset($this->request->headers['origin']),
  67. 'secure' => ! empty($this->request->connection->encrypted),
  68. 'issued' => time(),
  69. 'url' => $this->request->url ?? '',
  70. 'query' => $query,
  71. ];
  72. }
  73. public function __get($name)
  74. {
  75. if ($name === 'broadcast') {
  76. $this->flags['broadcast'] = true;
  77. return $this;
  78. }
  79. return null;
  80. }
  81. /**
  82. * @throws Exception
  83. */
  84. public function emit($ev = null)
  85. {
  86. $args = func_get_args();
  87. if (isset(self::$events[$ev])) {
  88. call_user_func_array(array(get_parent_class(__CLASS__), 'emit'), $args);
  89. } else {
  90. $packet = [];
  91. $packet['type'] = Parser::EVENT;
  92. $packet['data'] = $args;
  93. $flags = $this->flags;
  94. // access last argument to see if it's an ACK callback
  95. if (is_callable(end($args))) {
  96. if ($this->_rooms || isset($flags['broadcast'])) {
  97. throw new Exception('Callbacks are not supported when broadcasting');
  98. }
  99. echo('emitting packet with ack id ' . $this->nsp->ids);
  100. $this->acks[$this->nsp->ids] = array_pop($args);
  101. $packet['id'] = $this->nsp->ids++;
  102. }
  103. if ($this->_rooms || ! empty($flags['broadcast'])) {
  104. $this->adapter->broadcast(
  105. $packet,
  106. [
  107. 'except' => [$this->id => $this->id],
  108. 'rooms' => $this->_rooms,
  109. 'flags' => $flags
  110. ]
  111. );
  112. } else {
  113. // dispatch packet
  114. $this->packet($packet);
  115. }
  116. // reset flags
  117. $this->_rooms = [];
  118. $this->flags = [];
  119. }
  120. return $this;
  121. }
  122. /**
  123. * Targets a room when broadcasting.
  124. *
  125. * @param {String} name
  126. * @return Socket {Socket} self
  127. * @api public
  128. */
  129. public function to($name): Socket
  130. {
  131. if (! isset($this->_rooms[$name])) {
  132. $this->_rooms[$name] = $name;
  133. }
  134. return $this;
  135. }
  136. public function in($name): Socket
  137. {
  138. return $this->to($name);
  139. }
  140. /**
  141. * Sends a `message` event.
  142. *
  143. * @return Socket {Socket} self
  144. * @api public
  145. */
  146. public function send(): Socket
  147. {
  148. $args = func_get_args();
  149. array_unshift($args, 'message');
  150. call_user_func_array([$this, 'emit'], $args);
  151. return $this;
  152. }
  153. public function write(): Socket
  154. {
  155. $args = func_get_args();
  156. array_unshift($args, 'message');
  157. call_user_func_array([$this, 'emit'], $args);
  158. return $this;
  159. }
  160. /**
  161. * Writes a packet.
  162. *
  163. * @param {Object} packet object
  164. * @param {Object} options
  165. * @api private
  166. */
  167. public function packet($packet, $preEncoded = false)
  168. {
  169. if (! $this->nsp || ! $this->client) {
  170. return;
  171. }
  172. $packet['nsp'] = $this->nsp->name;
  173. $this->client->packet($packet, $preEncoded, false);
  174. }
  175. /**
  176. * Joins a room.
  177. *
  178. * @param {String} room
  179. * @return Socket {Socket} self
  180. * @api private
  181. */
  182. public function join($room): Socket
  183. {
  184. if (! $this->connected) {
  185. return $this;
  186. }
  187. if (isset($this->rooms[$room])) {
  188. return $this;
  189. }
  190. $this->adapter->add($this->id, $room);
  191. $this->rooms[$room] = $room;
  192. return $this;
  193. }
  194. /**
  195. * Leaves a room.
  196. *
  197. * @param {String} room
  198. * @return Socket {Socket} self
  199. * @api private
  200. */
  201. public function leave($room): Socket
  202. {
  203. $this->adapter->del($this->id, $room);
  204. unset($this->rooms[$room]);
  205. return $this;
  206. }
  207. /**
  208. * Leave all rooms.
  209. *
  210. * @api private
  211. */
  212. public function leaveAll()
  213. {
  214. $this->adapter->delAll($this->id);
  215. $this->rooms = [];
  216. }
  217. /**
  218. * Called by `Namespace` upon succesful
  219. * middleware execution (ie: authorization).
  220. *
  221. * @api private
  222. */
  223. public function onconnect()
  224. {
  225. $this->nsp->connected[$this->id] = $this;
  226. $this->join($this->id);
  227. $this->packet(
  228. [
  229. 'type' => Parser::CONNECT
  230. ]
  231. );
  232. }
  233. /**
  234. * Called with each packet. Called by `Client`.
  235. *
  236. * @param {Object} packet
  237. * @throws Exception
  238. * @api private
  239. */
  240. public function onpacket($packet)
  241. {
  242. switch ($packet['type']) {
  243. case Parser::BINARY_EVENT:
  244. case Parser::EVENT:
  245. $this->onevent($packet);
  246. break;
  247. case Parser::BINARY_ACK:
  248. case Parser::ACK:
  249. $this->onack($packet);
  250. break;
  251. case Parser::DISCONNECT:
  252. $this->ondisconnect();
  253. break;
  254. case Parser::ERROR:
  255. $this->emit('error', $packet['data']);
  256. }
  257. }
  258. /**
  259. * Called upon event packet.
  260. *
  261. * @param {Object} packet object
  262. * @api private
  263. */
  264. public function onevent($packet)
  265. {
  266. $args = $packet['data'] ?? [];
  267. if (! empty($packet['id']) || (isset($packet['id']) && $packet['id'] === 0)) {
  268. $args[] = $this->ack($packet['id']);
  269. }
  270. call_user_func_array(array(get_parent_class(__CLASS__), 'emit'), $args);
  271. }
  272. /**
  273. * Produces an ack callback to emit with an event.
  274. *
  275. * @param {Number} packet id
  276. * @api private
  277. */
  278. public function ack($id): Closure
  279. {
  280. $sent = false;
  281. return function () use (&$sent, $id) {
  282. $self = $this;
  283. // prevent double callbacks
  284. if ($sent) {
  285. return;
  286. }
  287. $args = func_get_args();
  288. $type = $this->hasBin($args) ? Parser::BINARY_ACK : Parser::ACK;
  289. $self->packet(
  290. [
  291. 'id' => $id,
  292. 'type' => $type,
  293. 'data' => $args
  294. ]
  295. );
  296. };
  297. }
  298. /**
  299. * Called upon ack packet.
  300. *
  301. * @api private
  302. */
  303. public function onack($packet)
  304. {
  305. $ack = $this->acks[$packet['id']];
  306. if (is_callable($ack)) {
  307. call_user_func($ack, $packet['data']);
  308. unset($this->acks[$packet['id']]);
  309. } else {
  310. echo('bad ack ' . $packet['id']);
  311. }
  312. }
  313. /**
  314. * Called upon client disconnect packet.
  315. *
  316. * @throws Exception
  317. * @api private
  318. */
  319. public function ondisconnect()
  320. {
  321. $this->onclose('client namespace disconnect');
  322. }
  323. /**
  324. * Handles a client error.
  325. *
  326. * @throws Exception
  327. * @api private
  328. */
  329. public function onerror($err)
  330. {
  331. if ($this->listeners('error')) {
  332. $this->emit('error', $err);
  333. }
  334. }
  335. /**
  336. * Called upon closing. Called by `Client`.
  337. *
  338. * @param {String} reason
  339. * @param {Error} optional error object
  340. * @throws Exception
  341. * @api private
  342. */
  343. public function onclose($reason)
  344. {
  345. if (! $this->connected) {
  346. return $this;
  347. }
  348. $this->emit('disconnect', $reason);
  349. $this->leaveAll();
  350. $this->nsp->remove($this);
  351. $this->client->remove($this);
  352. $this->connected = false;
  353. $this->disconnected = true;
  354. unset($this->nsp->connected[$this->id]);
  355. // ....
  356. $this->nsp = null;
  357. $this->server = null;
  358. $this->adapter = null;
  359. $this->request = null;
  360. $this->client = null;
  361. $this->conn = null;
  362. $this->removeAllListeners();
  363. }
  364. /**
  365. * Produces an `error` packet.
  366. *
  367. * @param {Object} error object
  368. * @api private
  369. */
  370. public function error($err)
  371. {
  372. $this->packet(
  373. [
  374. 'type' => Parser::ERROR, 'data' => $err
  375. ]
  376. );
  377. }
  378. /**
  379. * Disconnects this client.
  380. *
  381. * @param bool $close
  382. * @return Socket {Socket} self
  383. * @throws Exception
  384. * @api public
  385. */
  386. public function disconnect(bool $close = false): Socket
  387. {
  388. if (! $this->connected) {
  389. return $this;
  390. }
  391. if ($close) {
  392. $this->client->disconnect();
  393. } else {
  394. $this->packet(
  395. [
  396. 'type' => Parser::DISCONNECT
  397. ]
  398. );
  399. $this->onclose('server namespace disconnect');
  400. }
  401. return $this;
  402. }
  403. /**
  404. * Sets the compress flag.
  405. *
  406. * @param {Boolean} if `true`, compresses the sending data
  407. * @return Socket {Socket} self
  408. * @api public
  409. */
  410. public function compress($compress): Socket
  411. {
  412. $this->flags['compress'] = $compress;
  413. return $this;
  414. }
  415. protected function hasBin($args): bool
  416. {
  417. $hasBin = false;
  418. array_walk_recursive(
  419. $args,
  420. function ($item, $key) use ($hasBin) {
  421. if (! ctype_print($item)) {
  422. $hasBin = true;
  423. }
  424. }
  425. );
  426. return $hasBin;
  427. }
  428. }