/** * Parse received data * * @param $response */ private function parseData($response) { if (!$this->connected && isset($response['Sec-Websocket-Accept'])) { if (base64_encode(pack('H*', sha1($this->key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))) === $response['Sec-Websocket-Accept']) { $this->connected = true; } else { throw new \Exception("error response key."); } } return swoole_websocket_server::unpack($response); }
public function onReceive(\swoole_client $cli, $data) { if ($this->_status == self::CONNECT_SUCCESS) { if (!$this->_buffer) { $this->_buffer = new \swoole_buffer(strlen($data)); } if ($this->_buffer->capacity < strlen($data)) { $this->_buffer->expand(strlen($data)); } $this->_buffer->append($data); while (true) { if ($this->_recvWait) { if ($this->_buffer->length >= $this->_bufferOffset) { $isContinue = false; if ($this->_buffer->length > $this->_bufferOffset) { $data = $this->_buffer->substr(0, $this->_bufferOffset, true); $isContinue = true; } else { $data = $this->_buffer->read(0, $this->_bufferOffset); $this->_buffer->clear(); } $recv = \swoole_websocket_server::unpack($data); $this->_recvWait = false; $this->_bufferOffset = 0; $this->executeCoroutine($recv); if (!$this->next() || !$isContinue) { //当前中断不是websocket io中断或者buffer数据为空 break; } } else { break; } } else { $packageLength = $this->getPackageLength($this->_buffer); if (!$packageLength) { break; } if ($this->_buffer->capacity < $packageLength) { $this->_buffer->expand($packageLength); } $this->_bufferOffset = $packageLength; $this->_recvWait = true; if ($this->_buffer->length < $this->_bufferOffset) { break; } } } } else { try { $recv = $this->parseData($data); if ($recv) { $this->executeCoroutine($this); $this->next(); } } catch (\Exception $e) { $this->executeCoroutine(null, $e); $this->next(); } } }