| Total Complexity | 54 |
| Total Lines | 364 |
| Duplicated Lines | 0 % |
| Changes | 27 | ||
| Bugs | 2 | Features | 0 |
Complex classes like WebSocketServer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use WebSocketServer, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 19 | class WebSocketServer extends WssMain implements WebSocketServerContract |
||
| 20 | { |
||
| 21 | private const MAX_BYTES_READ = 8192; |
||
| 22 | private const HEADER_BYTES_READ = 1024; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * @var ServerConfig |
||
| 26 | */ |
||
| 27 | protected ServerConfig $config; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * @var array |
||
| 31 | */ |
||
| 32 | private array $clients = []; |
||
| 33 | |||
| 34 | /** |
||
| 35 | * @var array |
||
| 36 | */ |
||
| 37 | private array $headersUpgrade = []; |
||
| 38 | |||
| 39 | /** |
||
| 40 | * @var int |
||
| 41 | */ |
||
| 42 | private int $maxClients = 1; |
||
| 43 | |||
| 44 | /** |
||
| 45 | * @var WebSocket |
||
| 46 | */ |
||
| 47 | private WebSocket $handler; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @var bool |
||
| 51 | */ |
||
| 52 | private bool $stepRecursion = true; |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @var int |
||
| 56 | */ |
||
| 57 | private int $loopingDelay = 1000; |
||
| 58 | |||
| 59 | /** |
||
| 60 | * WebSocketServer constructor. |
||
| 61 | * |
||
| 62 | * @param WebSocket $handler |
||
| 63 | * @param ServerConfig $config |
||
| 64 | */ |
||
| 65 | public function __construct( |
||
| 66 | WebSocket $handler, |
||
| 67 | ServerConfig $config |
||
| 68 | ) |
||
| 69 | { |
||
| 70 | ini_set('default_socket_timeout', 5); // this should be >= 5 sec, otherwise there will be broken pipe - tested |
||
| 71 | |||
| 72 | $this->handler = $handler; |
||
| 73 | $this->config = $config; |
||
| 74 | $this->setIsPcntlLoaded(extension_loaded('pcntl')); |
||
| 75 | } |
||
| 76 | |||
| 77 | /** |
||
| 78 | * Set the looping sleep in microseconds |
||
| 79 | * |
||
| 80 | * @return self |
||
| 81 | */ |
||
| 82 | public function loopingDelay(int $loopingDelay): self |
||
| 83 | { |
||
| 84 | $this->loopingDelay = $loopingDelay; |
||
| 85 | |||
| 86 | return $this; |
||
| 87 | } |
||
| 88 | |||
| 89 | /** |
||
| 90 | * Runs main process - Anscestor with server socket on TCP |
||
| 91 | * |
||
| 92 | * @throws WebSocketException |
||
| 93 | * @throws ConnectionException |
||
| 94 | */ |
||
| 95 | public function run(): void |
||
| 96 | { |
||
| 97 | $context = stream_context_create(); |
||
| 98 | $errno = null; |
||
| 99 | $errorMessage = ''; |
||
| 100 | |||
| 101 | if ($this->config->isSsl() === true) { |
||
| 102 | stream_context_set_option($context, 'ssl', 'allow_self_signed', $this->config->getAllowSelfSigned()); |
||
| 103 | stream_context_set_option($context, 'ssl', 'verify_peer', false); |
||
| 104 | |||
| 105 | if (is_file($this->config->getLocalCert()) === false || is_file($this->config->getLocalPk()) === false) { |
||
| 106 | throw new WebSocketException('SSL certificates must be valid pem files', CommonsContract::SERVER_INVALID_STREAM_CONTEXT); |
||
| 107 | } |
||
| 108 | $isLocalCertSet = stream_context_set_option($context, 'ssl', 'local_cert', $this->config->getLocalCert()); |
||
| 109 | $isLocalPkSet = stream_context_set_option($context, 'ssl', 'local_pk', $this->config->getLocalPk()); |
||
| 110 | |||
| 111 | if ($isLocalCertSet === false || $isLocalPkSet === false) { |
||
| 112 | throw new WebSocketException('SSL certificates could not be set correctly', CommonsContract::SERVER_INVALID_STREAM_CONTEXT); |
||
| 113 | } |
||
| 114 | } |
||
| 115 | |||
| 116 | $server = stream_socket_server("tcp://{$this->config->getHost()}:{$this->config->getPort()}", $errno, |
||
| 117 | $errorMessage, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context); |
||
| 118 | |||
| 119 | if ($server === false) { |
||
| 120 | throw new WebSocketException('Could not bind to socket: ' . $errno . ' - ' . $errorMessage . PHP_EOL, |
||
| 121 | CommonsContract::SERVER_COULD_NOT_BIND_TO_SOCKET); |
||
| 122 | } |
||
| 123 | |||
| 124 | @cli_set_process_title($this->config->getProcessName()); |
||
|
|
|||
| 125 | $this->eventLoop($server); |
||
| 126 | } |
||
| 127 | |||
| 128 | /** |
||
| 129 | * Recursive event loop that input intu recusion by remainder = 0 - thus when N users, |
||
| 130 | * and when forks equals true which prevents it from infinite recursive iterations |
||
| 131 | * |
||
| 132 | * @param resource $server server connection |
||
| 133 | * @param bool $fork flag to fork or run event loop |
||
| 134 | * @throws WebSocketException |
||
| 135 | * @throws ConnectionException |
||
| 136 | */ |
||
| 137 | private function eventLoop($server, bool $fork = false): void |
||
| 138 | { |
||
| 139 | if ($fork === true && $this->isPcntlLoaded()) { |
||
| 140 | $pid = pcntl_fork(); |
||
| 141 | |||
| 142 | if ($pid) { // run eventLoop in parent |
||
| 143 | @cli_set_process_title($this->config->getProcessName()); |
||
| 144 | $this->eventLoop($server); |
||
| 145 | } |
||
| 146 | } else { |
||
| 147 | $this->looping($server); |
||
| 148 | } |
||
| 149 | } |
||
| 150 | |||
| 151 | /** |
||
| 152 | * @param resource $server |
||
| 153 | * @throws WebSocketException |
||
| 154 | * @throws ConnectionException |
||
| 155 | */ |
||
| 156 | private function looping($server): void |
||
| 157 | { |
||
| 158 | while (true) { |
||
| 159 | usleep($this->loopingDelay); |
||
| 160 | |||
| 161 | $totalClients = count($this->clients) + 1; |
||
| 162 | |||
| 163 | // maxClients prevents process fork on count down |
||
| 164 | if ($totalClients > $this->maxClients) { |
||
| 165 | $this->maxClients = $totalClients; |
||
| 166 | } |
||
| 167 | |||
| 168 | $doFork = $this->config->isForking() === true |
||
| 169 | && $totalClients !== 0 // avoid 0 process creation |
||
| 170 | && $this->stepRecursion === true // only once |
||
| 171 | && $this->maxClients === $totalClients // only if stack grows |
||
| 172 | && $totalClients % $this->config->getClientsPerFork() === 0; // only when N is there |
||
| 173 | if ($doFork) { |
||
| 174 | $this->stepRecursion = false; |
||
| 175 | $this->eventLoop($server, true); |
||
| 176 | } |
||
| 177 | $this->lessConnThanProc($totalClients, $this->maxClients); |
||
| 178 | |||
| 179 | //prepare readable sockets |
||
| 180 | $readSocks = $this->clients; |
||
| 181 | $readSocks[] = $server; |
||
| 182 | $this->cleanSocketResources($readSocks); |
||
| 183 | |||
| 184 | //start reading and use a large timeout |
||
| 185 | if (!stream_select($readSocks, $write, $except, $this->config->getStreamSelectTimeout())) { |
||
| 186 | throw new WebSocketException('something went wrong while selecting', |
||
| 187 | CommonsContract::SERVER_SELECT_ERROR); |
||
| 188 | } |
||
| 189 | |||
| 190 | //new client |
||
| 191 | if (in_array($server, $readSocks, false)) { |
||
| 192 | $this->acceptNewClient($server, $readSocks); |
||
| 193 | if ($this->config->isCheckOrigin() && $this->config->isOriginHeader() === false) { |
||
| 194 | continue; |
||
| 195 | } |
||
| 196 | } |
||
| 197 | |||
| 198 | //message from existing client |
||
| 199 | $this->messagesWorker($readSocks); |
||
| 200 | } |
||
| 201 | } |
||
| 202 | |||
| 203 | /** |
||
| 204 | * @param resource $server |
||
| 205 | * @param array $readSocks |
||
| 206 | * @throws ConnectionException |
||
| 207 | */ |
||
| 208 | private function acceptNewClient($server, array &$readSocks): void |
||
| 209 | { |
||
| 210 | $newClient = stream_socket_accept($server, -1); // must be 0 to non-block |
||
| 211 | if ($newClient) { |
||
| 212 | if ($this->config->isSsl() === true) { |
||
| 213 | $isEnabled = stream_socket_enable_crypto($newClient, true, $this->config->getCryptoType()); |
||
| 214 | if ($isEnabled === false) { // couldn't enable crypto - let's try one more time |
||
| 215 | return; |
||
| 216 | } |
||
| 217 | } |
||
| 218 | |||
| 219 | // important to read from headers here coz later client will change and there will be only msgs on pipe |
||
| 220 | $headers = fread($newClient, self::HEADER_BYTES_READ); |
||
| 221 | if ($this->config->isCheckOrigin()) { |
||
| 222 | $hasOrigin = (new OriginComponent($this->config, $newClient))->checkOrigin($headers); |
||
| 223 | $this->config->setOriginHeader($hasOrigin); |
||
| 224 | if ($hasOrigin === false) { |
||
| 225 | return; |
||
| 226 | } |
||
| 227 | } |
||
| 228 | |||
| 229 | if (empty($this->handler->pathParams[0]) === false) { |
||
| 230 | $this->setPathParams($headers); |
||
| 231 | } |
||
| 232 | |||
| 233 | $this->clients[] = $newClient; |
||
| 234 | $this->stepRecursion = true; // set on new client - remainder % is always 0 |
||
| 235 | |||
| 236 | // trigger OPEN event |
||
| 237 | $this->handler->onOpen(new Connection($newClient, $this->clients)); |
||
| 238 | $this->handshake($newClient, $headers); |
||
| 239 | } |
||
| 240 | |||
| 241 | //delete the server socket from the read sockets |
||
| 242 | unset($readSocks[array_search($server, $readSocks, false)]); |
||
| 243 | } |
||
| 244 | |||
| 245 | /** |
||
| 246 | * @param array $readSocks |
||
| 247 | * @uses onPing |
||
| 248 | * @uses onPong |
||
| 249 | * @uses onMessage |
||
| 250 | */ |
||
| 251 | private function messagesWorker(array $readSocks): void |
||
| 252 | { |
||
| 253 | foreach ($readSocks as $kSock => $sock) { |
||
| 254 | $data = $this->decode(fread($sock, self::MAX_BYTES_READ)); |
||
| 255 | if ($data !== null) { |
||
| 256 | $dataType = null; |
||
| 257 | $dataPayload = null; |
||
| 258 | if ($data !== false) { // payload is too large - waiting for remained data |
||
| 259 | $dataType = $data['type']; |
||
| 260 | $dataPayload = $data['payload']; |
||
| 261 | } |
||
| 262 | |||
| 263 | // to manipulate connection through send/close methods via handler, specified in IConnection |
||
| 264 | $cureentConn = new Connection($sock, $this->clients); |
||
| 265 | if (empty($data) || $dataType === self::EVENT_TYPE_CLOSE) { // close event triggered from client - browser tab or close socket event |
||
| 266 | // trigger CLOSE event |
||
| 267 | try { |
||
| 268 | $this->handler->onClose($cureentConn); |
||
| 269 | } catch (WebSocketException $e) { |
||
| 270 | $e->printStack(); |
||
| 271 | } |
||
| 272 | |||
| 273 | // to avoid event leaks |
||
| 274 | unset($this->clients[array_search($sock, $this->clients)], $readSocks[$kSock]); |
||
| 275 | continue; |
||
| 276 | } |
||
| 277 | |||
| 278 | $isSupportedMethod = empty(self::MAP_EVENT_TYPE_TO_METHODS[$dataType]) === false |
||
| 279 | && method_exists($this->handler, self::MAP_EVENT_TYPE_TO_METHODS[$dataType]); |
||
| 280 | if ($isSupportedMethod) { |
||
| 281 | try { |
||
| 282 | // dynamic call: onMessage, onPing, onPong |
||
| 283 | $this->handler->{self::MAP_EVENT_TYPE_TO_METHODS[$dataType]}($cureentConn, $dataPayload); |
||
| 284 | } catch (WebSocketException $e) { |
||
| 285 | $e->printStack(); |
||
| 286 | } |
||
| 287 | } |
||
| 288 | } |
||
| 289 | } |
||
| 290 | } |
||
| 291 | |||
| 292 | /** |
||
| 293 | * Handshakes/upgrade and key parse |
||
| 294 | * |
||
| 295 | * @param resource $client Source client socket to write |
||
| 296 | * @param string $headers Headers that client has been sent |
||
| 297 | * @return string socket handshake key (Sec-WebSocket-Key)| false on parse error |
||
| 298 | * @throws ConnectionException |
||
| 299 | */ |
||
| 300 | private function handshake($client, string $headers): string |
||
| 301 | { |
||
| 302 | $match = []; |
||
| 303 | preg_match(self::SEC_WEBSOCKET_KEY_PTRN, $headers, $match); |
||
| 304 | if (empty($match[1])) { |
||
| 305 | return ''; |
||
| 306 | } |
||
| 307 | |||
| 308 | $key = $match[1]; |
||
| 309 | // sending header according to WebSocket Protocol |
||
| 310 | $secWebSocketAccept = base64_encode(sha1(trim($key) . self::HEADER_WEBSOCKET_ACCEPT_HASH, true)); |
||
| 311 | $this->setHeadersUpgrade($secWebSocketAccept); |
||
| 312 | $upgradeHeaders = $this->getHeadersUpgrade(); |
||
| 313 | |||
| 314 | fwrite($client, $upgradeHeaders); |
||
| 315 | |||
| 316 | return $key; |
||
| 317 | } |
||
| 318 | |||
| 319 | /** |
||
| 320 | * Sets an array of headers needed to upgrade server/client connection |
||
| 321 | * |
||
| 322 | * @param string $secWebSocketAccept base64 encoded Sec-WebSocket-Accept header |
||
| 323 | */ |
||
| 324 | private function setHeadersUpgrade(string $secWebSocketAccept): void |
||
| 325 | { |
||
| 326 | $this->headersUpgrade = [ |
||
| 327 | self::HEADERS_UPGRADE_KEY => self::HEADERS_UPGRADE_VALUE, |
||
| 328 | self::HEADERS_CONNECTION_KEY => self::HEADERS_CONNECTION_VALUE, |
||
| 329 | self::HEADERS_SEC_WEBSOCKET_ACCEPT_KEY => ' ' . $secWebSocketAccept |
||
| 330 | // the space before key is really important |
||
| 331 | ]; |
||
| 332 | } |
||
| 333 | |||
| 334 | /** |
||
| 335 | * Retreives headers from an array of headers to upgrade server/client connection |
||
| 336 | * |
||
| 337 | * @return string Headers to Upgrade communication connection |
||
| 338 | * @throws ConnectionException |
||
| 339 | */ |
||
| 340 | private function getHeadersUpgrade(): string |
||
| 341 | { |
||
| 342 | $handShakeHeaders = self::HEADER_HTTP1_1 . self::HEADERS_EOL; |
||
| 343 | if (empty($this->headersUpgrade)) { |
||
| 344 | throw new ConnectionException('Headers for upgrade handshake are not set' . PHP_EOL, |
||
| 345 | CommonsContract::SERVER_HEADERS_NOT_SET); |
||
| 346 | } |
||
| 347 | |||
| 348 | foreach ($this->headersUpgrade as $key => $header) { |
||
| 349 | $handShakeHeaders .= $key . ':' . $header . self::HEADERS_EOL; |
||
| 350 | if ($key === self::HEADERS_SEC_WEBSOCKET_ACCEPT_KEY) { // add additional EOL fo Sec-WebSocket-Accept |
||
| 351 | $handShakeHeaders .= self::HEADERS_EOL; |
||
| 352 | } |
||
| 353 | } |
||
| 354 | |||
| 355 | return $handShakeHeaders; |
||
| 356 | } |
||
| 357 | |||
| 358 | /** |
||
| 359 | * Parses parameters from GET on web-socket client connection before handshake |
||
| 360 | * |
||
| 361 | * @param string $headers |
||
| 362 | */ |
||
| 363 | private function setPathParams(string $headers): void |
||
| 383 | } |
||
| 384 | } |
||
| 385 | } |
||
| 386 | } |
||
| 387 |
If you suppress an error, we recommend checking for the error condition explicitly: