socket.class.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. $res = socket_bind($this->socket, $this->address);
  75. $this->throw_if($res);
  76. if(!file_exists($this->address)){
  77. throw new \Exception('Unable to create socket file');
  78. }
  79. chmod($this->address, 0702);
  80. unlink($this->address); // Delete when we are done
  81. }else{
  82. $this->throw_if(socket_bind($this->socket, $this->address, $this->port));
  83. }
  84. $this->fire('bind', $this);
  85. $this->throw_if(socket_listen($this->socket, $this->max_connections));
  86. $this->fire('listen', $this);
  87. }elseif($this->socket_type == static::CLIENT){
  88. if(is_null($this->port)){
  89. $res = socket_connect($this->socket, $this->address);
  90. }else{
  91. $res = socket_connect($this->socket, $this->address, $this->port);
  92. }
  93. $this->throw_if($res);
  94. }else{
  95. throw new \Exception("Invalid socket type {$this->socket_type}");
  96. }
  97. $this->open = true;
  98. $this->fire('open', $this);
  99. return $this;
  100. }
  101. public function handle(int $length = 2048, bool $binary = false){
  102. if(!$this->open){
  103. $this->open();
  104. }
  105. socket_set_nonblock($this->socket);
  106. if($this->socket_type == static::SERVER){
  107. $regex = $binary ? '/\0/' : '/[\n\r]/';
  108. $type = $binary ? PHP_BINARY_READ : PHP_NORMAL_READ;
  109. do{
  110. $socket = socket_accept($this->socket);
  111. if($socket === false){
  112. usleep(100);
  113. }elseif($socket > 0){
  114. socket_set_nonblock($socket);
  115. $client = [$socket, ''];
  116. $this->clients[] = $client;
  117. $this->fire('connect', $this, $client);
  118. }else{
  119. $error = trim(socket_strerror($socket));
  120. if($error !== 'A non-blocking socket operation could not be completed immediately.'){
  121. $this->fire('error', $this, new \Exception($error));
  122. $this->open = false;
  123. }
  124. }
  125. $this->fire('tick', $this);
  126. if($this->open){
  127. foreach($this->clients as $client){
  128. $data = socket_read($client[0], $length, $type);
  129. if($data === false){
  130. $this->drop($client);
  131. }else{
  132. if(strlen($data) > 0 && $this->fire('data', $this, $data, $client) !== false){
  133. $client[1] .= $data;
  134. }
  135. $pos = preg_match($regex, $data, $matches, PREG_OFFSET_CAPTURE) == 1 ? $matches[0][1] : false;
  136. if($pos === strlen($data) - 1){
  137. $this->fire('read', $this, substr($client[1], 0, -1), $client);
  138. $client[1] = '';
  139. }
  140. }
  141. $this->fire('tick', $this);
  142. if($this->open === false){
  143. break;
  144. }
  145. }
  146. }
  147. }while($this->open);
  148. }elseif($this->socket_type == static::CLIENT){
  149. while($this->open && $this->read($length, $binary) !== false){};
  150. }
  151. socket_set_block($this->socket);
  152. $this->close(true);
  153. return $this;
  154. }
  155. public function write(string $data, bool $binary = false){
  156. if(!$this->open){
  157. throw new \Exception("You can't write to a socket that isn't open");
  158. }
  159. $stop = $binary ? "\0" : "\n";
  160. if($this->fire('write', $this, $data) !== false){
  161. $this->throw_if(socket_write($this->socket, $data.$stop));
  162. }
  163. return $this;
  164. }
  165. public function read(int $length = 2048, bool $binary = false){
  166. if(!$this->open){
  167. return false;
  168. }
  169. $regex = $binary ? '/\0/' : '/[\n\r]/';
  170. $type = $binary ? PHP_BINARY_READ : PHP_NORMAL_READ;
  171. $line = '';
  172. do{
  173. $data = socket_read($this->socket, $length, $type);
  174. if($data === false){
  175. $this->open = false;
  176. }elseif(strlen($data) > 0 && $this->fire('data', $this, $data) !== false){
  177. $line .= $data;
  178. }
  179. $pos = preg_match($regex, $data, $matches, PREG_OFFSET_CAPTURE) == 1 ? $matches[0][1] : false;
  180. }while($pos !== strlen($data) - 1 && $this->open !== false);
  181. $line = substr($line, 0, -1);
  182. $this->fire('read', $this, $line);
  183. return $line;
  184. }
  185. public function client_write(array $client, $data, bool $binary = false){
  186. if(!$this->open){
  187. throw new \Exception("You can't write to a socket that isn't open");
  188. }
  189. $stop = $binary ? "\0" : "\n";
  190. if($this->fire('write', $this, $data) !== false){
  191. $this->throw_if(socket_write($client[0], $data.$stop));
  192. }
  193. return $this;
  194. }
  195. public function close(bool $event = false){
  196. foreach($this->clients as $client){
  197. $this->drop($client);
  198. }
  199. socket_close($this->socket);
  200. $this->open = false;
  201. $this->fire('close', $this);
  202. return $this;
  203. }
  204. public function drop($client){
  205. socket_close($client[0]);
  206. if(in_array($client, $this->clients)){
  207. array_splice($this->clients, array_search($client, $this->clients), 1);
  208. $this->fire('disconnect', $this, $client);
  209. }
  210. }
  211. }
  212. ?>