public function send(string $data, int $type = Protocol::TYPE_TEXT): bool
    {
        if (!$this->handshaked) {
            throw new HandshakeException('Connection is not handshaked');
        }

        $payload = $this->protocol->getPayload();
        if (!is_scalar($data) && !$data instanceof Payload) {
            $data = json_encode($data);
        }

        // Servers don't send masked payloads
        $payload->encode($data, $type, false);

        if (!$payload->sendToSocket($this->socket)) {
            $this->logger->warning('Could not send payload to client');
            throw new ConnectionException('Could not send data to connection: ' . $this->socket->getLastError());
        }

        return true;
    }