socket.class.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. namespace Juju\Net;
  3. use Juju\Events;
  4. require_once(dirname(__DIR__).'/events.trait.php');
  5. class Socket {
  6. use Events;
  7. private $socket;
  8. private $clients;
  9. private $dsn;
  10. private $socket_type;
  11. private $open;
  12. const SERVER = 0;
  13. const CLIENT = 1;
  14. public static function from(string $dsnstring, bool $listen = false){
  15. return new Socket($dsnstring, $listen);
  16. }
  17. private function __construct(string $dsnstring, bool $listen = false){
  18. $parts = explode('://', $dsnstring);
  19. $dsnstring = $parts[1];
  20. $dsn = explode(';', $dsnstring);
  21. $dsn = array_reduce($dsn, function($dsn, $item){
  22. $item = explode('=', $item);
  23. $dsn[$item[0]] = $item[1];
  24. return $dsn;
  25. });
  26. $this->dsn = [
  27. 'protocol'=> $parts[0] ?? null,
  28. 'domain'=> strtoupper($dsn['domain']) ?? 'UNIX',
  29. 'type'=> strtoupper($dsn['type']) ?? 'STREAM',
  30. 'address'=> $dsn['address'] ?? '127.0.0.1',
  31. 'port'=> $dsn['port'] ?? null,
  32. 'max_connections'=> $dsn['max_connections'] ?? 5
  33. ];
  34. $this->socket_type = $listen ? static::SERVER : static::CLIENT;
  35. $this->open = false;
  36. if($listen){
  37. $this->clients = [];
  38. }
  39. }
  40. public function __get($name){
  41. switch($name){
  42. case 'socket':case 'dsn':case 'socket_type':case 'open':
  43. return $this->$name;
  44. break;
  45. case 'protocol':case 'domain':case 'type':case 'address':case 'port':case 'max_connections':
  46. return $this->dsn[$name];
  47. break;
  48. case 'error':
  49. return socket_strerror(socket_last_error());
  50. break;
  51. default:
  52. throw new \Exception("Property {$name} does not exist");
  53. }
  54. }
  55. public function __set($name, $value){
  56. throw new \Exception("Property {$name} does not exist or is read only");
  57. }
  58. private function throw_if($bool){
  59. if($bool === false){
  60. $this->throw();
  61. }
  62. }
  63. private function throw(){
  64. $error = new \Exception($this->error);
  65. if($this->fire('error', $this, $error) !== false){
  66. throw $error;
  67. }
  68. }
  69. public function open(){
  70. $this->socket = socket_create(constant("AF_{$this->dsn['protocol']}"), constant("SOCK_{$this->dsn['type']}"), is_null($this->dsn['protocol']) ? 0 : getprotobyname($this->dsn['protocol']));
  71. $this->throw_if($this->socket);
  72. if($this->socket_type == static::SERVER){
  73. if(is_null($this->port)){
  74. socket_bind($this->socket, $this->address);
  75. }else{
  76. $res = socket_bind($this->socket, $this->address, $this->port);
  77. }
  78. $this->throw_if($res);
  79. $this->fire('bind', $this);
  80. $this->throw_if(socket_listen($this->socket, $this->max_connections));
  81. $this->fire('listen', $this);
  82. }elseif($this->socket_type == static::CLIENT){
  83. if(is_null($this->port)){
  84. socket_connect($this->socket, $this->address);
  85. }else{
  86. $res = socket_connect($this->socket, $this->address, $this->port);
  87. }
  88. $this->throw_if($res);
  89. }else{
  90. throw new \Exception("Invalid socket type {$this->socket_type}");
  91. }
  92. $this->open = true;
  93. $this->fire('open', $this);
  94. return $this;
  95. }
  96. public function handle(int $length = 2048, bool $binary = false){
  97. if(!$this->open){
  98. $this->open();
  99. }
  100. socket_set_nonblock($this->socket);
  101. if($this->socket_type == static::SERVER){
  102. $regex = $binary ? '/\0/' : '/[\n\r]/';
  103. $type = $binary ? PHP_BINARY_READ : PHP_NORMAL_READ;
  104. do{
  105. $socket = socket_accept($this->socket);
  106. if($socket === false){
  107. usleep(100);
  108. }elseif($socket > 0){
  109. socket_set_nonblock($socket);
  110. $client = [$socket, ''];
  111. $this->clients[] = $client;
  112. $this->fire('connect', $this, $client);
  113. }else{
  114. $error = trim(socket_strerror($socket));
  115. if($error !== 'A non-blocking socket operation could not be completed immediately.'){
  116. $this->fire('error', $this, new \Exception($error));
  117. $this->open = false;
  118. }
  119. }
  120. $this->fire('tick', $this);
  121. if($this->open){
  122. foreach($this->clients as $client){
  123. $data = socket_read($client[0], $length, $type);
  124. if($data === false){
  125. $this->drop($client);
  126. }else{
  127. if(strlen($data) > 0 && $this->fire('data', $this, $data, $client) !== false){
  128. $client[1] .= $data;
  129. }
  130. $pos = preg_match($regex, $data, $matches, PREG_OFFSET_CAPTURE) == 1 ? $matches[0][1] : false;
  131. if($pos === strlen($data) - 1){
  132. $this->fire('read', $this, substr($client[1], 0, -1), $client);
  133. $client[1] = '';
  134. }
  135. }
  136. $this->fire('tick', $this);
  137. if($this->open === false){
  138. break;
  139. }
  140. }
  141. }
  142. }while($this->open);
  143. }elseif($this->socket_type == static::CLIENT){
  144. while($this->open && $this->read($length, $binary) !== false){};
  145. }
  146. socket_set_block($this->socket);
  147. $this->close(true);
  148. return $this;
  149. }
  150. public function write(string $data, bool $binary = false){
  151. if(!$this->open){
  152. throw new \Exception("You can't write to a socket that isn't open");
  153. }
  154. $stop = $binary ? "\0" : "\n";
  155. if($this->fire('write', $this, $data) !== false){
  156. $this->throw_if(socket_write($this->socket, $data.$stop));
  157. }
  158. return $this;
  159. }
  160. public function read(int $length = 2048, bool $binary = false){
  161. if(!$this->open){
  162. return false;
  163. }
  164. $regex = $binary ? '/\0/' : '/[\n\r]/';
  165. $type = $binary ? PHP_BINARY_READ : PHP_NORMAL_READ;
  166. $line = '';
  167. do{
  168. $data = socket_read($this->socket, $length, $type);
  169. if($data === false){
  170. $this->open = false;
  171. }elseif(strlen($data) > 0 && $this->fire('data', $this, $data) !== false){
  172. $line .= $data;
  173. }
  174. $pos = preg_match($regex, $data, $matches, PREG_OFFSET_CAPTURE) == 1 ? $matches[0][1] : false;
  175. }while($pos !== strlen($data) - 1 && $this->open !== false);
  176. $line = substr($line, 0, -1);
  177. $this->fire('read', $this, $line);
  178. return $line;
  179. }
  180. public function client_write(array $client, $data, bool $binary = false){
  181. if(!$this->open){
  182. throw new \Exception("You can't write to a socket that isn't open");
  183. }
  184. $stop = $binary ? "\0" : "\n";
  185. if($this->fire('write', $this, $data) !== false){
  186. $this->throw_if(socket_write($client[0], $data.$stop));
  187. }
  188. return $this;
  189. }
  190. public function close(bool $event = false){
  191. foreach($this->clients as $client){
  192. $this->drop($client);
  193. }
  194. socket_close($this->socket);
  195. $this->open = false;
  196. $this->fire('close', $this);
  197. return $this;
  198. }
  199. public function drop($client){
  200. socket_close($client[0]);
  201. if(in_array($client, $this->clients)){
  202. array_splice($this->clients, array_search($client, $this->clients), 1);
  203. $this->fire('disconnect', $this, $client);
  204. }
  205. }
  206. }
  207. ?>