/** * @coroutine * * @param \Icicle\WebSocket\Protocol\Rfc6455Frame $frame * @param float|int $timeout * * @return \Generator * * @resolve int Number of bytes sent on the socket. */ public function send(Frame $frame, float $timeout = 0) : \Generator { $byte = $frame->getType(); if ($frame->isFinal()) { $byte |= self::BIT_FIN; } $byte |= $frame->getRsv(); $buffer = chr($byte); $size = $frame->getSize(); if ($size < self::TWO_BYTE_LENGTH_FLAG) { $length = $size; } elseif ($size < self::TWO_BYTE_MAX_LENGTH) { $length = self::TWO_BYTE_LENGTH_FLAG; } else { $length = self::EIGHT_BYTE_LENGTH_FLAG; } $byte = $length; if ($this->masked) { $byte |= self::MASK_FLAG_MASK; } $buffer .= chr($byte); if (self::TWO_BYTE_LENGTH_FLAG === $length) { $buffer .= pack('n', $size); } elseif (self::EIGHT_BYTE_LENGTH_FLAG === $length) { $buffer .= pack('NN', $size >> 32, $size); } $data = $frame->getData(); if ($this->masked) { $mask = random_bytes(self::MASK_LENGTH); $buffer .= $mask; $data ^= str_repeat($mask, (int) (($size + self::MASK_LENGTH - 1) / self::MASK_LENGTH)); } $written = (yield from $this->socket->write($buffer, $timeout)); return $written + (yield from $this->socket->write($data, $timeout)); }
/** * {@inheritdoc} */ public function writeRequest(Socket $socket, Request $request, float $timeout = 0) : \Generator { $written = (yield from $socket->write($this->encoder->encodeRequest($request))); $stream = $request->getBody(); if ($stream->isReadable()) { $written += (yield from Stream\pipe($stream, $socket, false, 0, null, $timeout)); } return $written; }