DefaultAdapter.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace PHPSocketIO;
  3. class DefaultAdapter
  4. {
  5. public $nsp = null;
  6. public $rooms = array();
  7. public $sids = array();
  8. public $encoder = null;
  9. public function __construct($nsp)
  10. {
  11. $this->nsp = $nsp;
  12. $this->encoder = new Parser\Encoder();
  13. Debug::debug('DefaultAdapter __construct');
  14. }
  15. public function __destruct()
  16. {
  17. Debug::debug('DefaultAdapter __destruct');
  18. }
  19. public function add($id, $room)
  20. {
  21. $this->sids[$id][$room] = true;
  22. $this->rooms[$room][$id] = true;
  23. }
  24. public function del($id, $room)
  25. {
  26. unset($this->sids[$id][$room]);
  27. unset($this->rooms[$room][$id]);
  28. if(empty($this->rooms[$room]))
  29. {
  30. unset($this->rooms[$room]);
  31. }
  32. }
  33. public function delAll($id)
  34. {
  35. $rooms = array_keys(isset($this->sids[$id]) ? $this->sids[$id] : array());
  36. foreach($rooms as $room)
  37. {
  38. $this->del($id, $room);
  39. }
  40. unset($this->sids[$id]);
  41. }
  42. public function broadcast($packet, $opts, $remote = false)
  43. {
  44. $rooms = isset($opts['rooms']) ? $opts['rooms'] : array();
  45. $except = isset($opts['except']) ? $opts['except'] : array();
  46. $flags = isset($opts['flags']) ? $opts['flags'] : array();
  47. $packetOpts = array(
  48. 'preEncoded' => true,
  49. 'volatile' => isset($flags['volatile']) ? $flags['volatile'] : null,
  50. 'compress' => isset($flags['compress']) ? $flags['compress'] : null
  51. );
  52. $packet['nsp'] = $this->nsp->name;
  53. $encodedPackets = $this->encoder->encode($packet);
  54. if($rooms)
  55. {
  56. $ids = array();
  57. foreach($rooms as $i=>$room)
  58. {
  59. if(!isset($this->rooms[$room]))
  60. {
  61. continue;
  62. }
  63. $room = $this->rooms[$room];
  64. foreach($room as $id=>$item)
  65. {
  66. if(isset($ids[$id]) || isset($except[$id]))
  67. {
  68. continue;
  69. }
  70. if(isset($this->nsp->connected[$id]))
  71. {
  72. $ids[$id] = true;
  73. $this->nsp->connected[$id]->packet($encodedPackets, $packetOpts);
  74. }
  75. }
  76. }
  77. } else {
  78. foreach($this->sids as $id=>$sid)
  79. {
  80. if(isset($except[$id])) continue;
  81. if(isset($this->nsp->connected[$id]))
  82. {
  83. $socket = $this->nsp->connected[$id];
  84. $volatile = isset($flags['volatile']) ? $flags['volatile'] : null;
  85. $socket->packet($encodedPackets, true, $volatile);
  86. }
  87. }
  88. }
  89. }
  90. public function clients($rooms, $fn) {
  91. $sids = array();
  92. foreach ($rooms as $room) {
  93. $sids = array_merge($sids, $this->rooms[$room]);
  94. }
  95. $fn();
  96. }
  97. }