From b0eac4814f3371455364a91b75707282b2fb8b6c Mon Sep 17 00:00:00 2001 From: Donal Byrne Date: Wed, 15 Jun 2016 15:12:46 +0200 Subject: [PATCH 1/2] Fix corrupt reads. Now continuously reads from stream in chunks until whole message is received --- src/Connection.php | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Connection.php b/src/Connection.php index 219e0dd..748ad7a 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -13,6 +13,12 @@ class Connection */ private $pings = 0; + /** + * Chunk size in bytes to use when reading with fread. + * @var int + */ + private $chunkSize = 8192; + /** * Return the number of pings. * @@ -159,7 +165,18 @@ private function receive($len = null) { if ($len) { - $line = fread($this->streamSocket, $len); + $chunkSize = $this->chunkSize; + $line = null; + $receivedBytes = 0; + while ($receivedBytes < $len) { + $bytesLeft = $len - $receivedBytes; + if ( $bytesLeft < 1500 ) { + $chunkSize = $bytesLeft; + } + + $line .= fread($this->streamSocket, $chunkSize); + $receivedBytes += $chunkSize; + } } else { $line = fgets($this->streamSocket); } @@ -425,6 +442,13 @@ public function reconnect() $this->connect(); } + /** + * @param integer $chunkSize Set byte chunk len to read when reading from wire + */ + public function setChunkSize($chunkSize){ + $this->chunkSize = $chunkSize; + } + /** * Close will close the connection to the server. * From 851d8819940ddbc0ed66a8e69e274495208c9001 Mon Sep 17 00:00:00 2001 From: Donal Byrne Date: Wed, 15 Jun 2016 17:48:55 +0200 Subject: [PATCH 2/2] Strips the escape chars at the end of fread --- src/Connection.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Connection.php b/src/Connection.php index 748ad7a..0994896 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -177,6 +177,9 @@ private function receive($len = null) $line .= fread($this->streamSocket, $chunkSize); $receivedBytes += $chunkSize; } + if (strlen($line) > 2) { + $line = substr($line, 0, -2); + } } else { $line = fgets($this->streamSocket); }