/** * Sends a Message over this transport * * @param Message $message * * @return int the number of TCP packets sent */ public function send(Message $message) { $rawMessage = $this->getMessageEncoder()->encode($message) . ""; // send message in one packet $this->socketClient->write($rawMessage); return 1; }
public function testWrite() { $testData = "Hello World!"; $numBytes = $this->socketClient->write($testData); $this->assertEquals(strlen($testData), $numBytes); // check that message is sent to server $readData = fread($this->serverSocket, $numBytes); $this->assertEquals($testData, $readData); }
/** * Sends a Message over this transport * * @param MessageInterface $message * * @return int the number of bytes sent */ public function send(MessageInterface $message) { $messageEncoder = $this->getMessageEncoder(); $rawMessage = $messageEncoder->encode($message); $request = array(sprintf("POST %s HTTP/1.1", $this->path), sprintf("Host: %s:%d", $this->host, $this->port), sprintf("Content-Length: %d", strlen($rawMessage)), "Content-Type: application/json", "Connection: Keep-Alive", "Accept: */*"); if (null !== $this->authentication) { $request[] = "Authorization: Basic " . base64_encode($this->authentication); } if ($messageEncoder instanceof CompressedJsonEncoder) { $request[] = "Content-Encoding: gzip"; } $request[] = ""; // blank line to separate headers from body $request[] = $rawMessage; $request = implode($request, "\r\n"); $byteCount = $this->socketClient->write($request); $headers = $this->readResponseHeaders(); // if we don't have a HTTP/1.1 connection, or the server decided to close the connection // we should do so as well. next read/write-attempt will open a new socket in this case. if (strpos($headers, "HTTP/1.1") !== 0 || preg_match("!Connection:\\s*Close!i", $headers)) { $this->socketClient->close(); } if (!preg_match("!^HTTP/1.\\d 202 Accepted!i", $headers)) { throw new RuntimeException(sprintf("Graylog-Server didn't answer properly, expected 'HTTP/1.x 202 Accepted', response is '%s'", trim($headers))); } return $byteCount; }
/** * Sends given string in multiple chunks * * @param string $rawMessage * @return int * * @throws RuntimeException on too large messages which would exceed the maximum number of possible chunks */ protected function sendMessageInChunks($rawMessage) { // split to chunks $chunks = str_split($rawMessage, $this->chunkSize); $numChunks = count($chunks); if ($numChunks > self::CHUNK_MAX_COUNT) { throw new RuntimeException(sprintf("Message is to big. Chunk count exceeds %d", self::CHUNK_MAX_COUNT)); } // generate a random 8byte-message-id $messageId = substr(md5(uniqid(), true), 0, 8); // send chunks with a correct chunk-header // @link http://graylog2.org/gelf#specs foreach ($chunks as $idx => $chunk) { $data = self::CHUNK_GELF_ID . $messageId . pack('CC', $idx, $numChunks) . $chunk; $this->socketClient->write($data); } return $numChunks; }