Socket.php 11 KB

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