Skip to content

Commit

Permalink
Make read length optional
Browse files Browse the repository at this point in the history
  • Loading branch information
valtzu committed Sep 18, 2024
1 parent 3901ddd commit 4ac84c6
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ $handshakeResponse = $guzzle->request('GET', 'wss://ws.postman-echo.com/raw');
$ws = $handshakeResponse->getBody();

$ws->write("Hello world");
$helloWorld = $ws->read(100); // This will block until the reply frame is received
$helloWorld = $ws->read(); // This will block until the reply frame is received
```

#### Asynchronous usage
Expand All @@ -39,7 +39,7 @@ $handshakeResponse = $guzzle->requestAsync('GET', 'wss://ws.postman-echo.com/raw
$ws = $handshakeResponse->getBody();

$ws->write("Hello world");
$helloWorld = $ws->read(100); // Here you may get an empty string if data wasn't received yet
$helloWorld = $ws->read(); // Here you may get an empty string if data wasn't received yet
```

#### Connection upkeep / ping-pong
Expand Down
6 changes: 4 additions & 2 deletions src/WebSocketStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@ public function isReadable(): bool
return $this->connection->isReadable();
}

public function read(int $length): string
public function read(?int $length = null): string
{
$length ??= ($this->buffer->getMetadata('hwm') - $this->buffer->getSize());

if ($length > 0 && $this->buffer->getSize() >= $length) {
return $this->buffer->read($length);
}
Expand Down Expand Up @@ -129,7 +131,7 @@ public function read(int $length): string

public function getContents(): string
{
return $this->connection->getContents();
return $this->read();
}

public function getMetadata(?string $key = null)
Expand Down
8 changes: 8 additions & 0 deletions tests/PostmanEchoServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public function synchronousOpenSendAndReceive()
$this->assertSame("lo", $ws->read(2));
$this->assertSame(6, $ws->write("Worlds"));
$this->assertSame("Worlds", $ws->read(128));
$this->assertSame(3, $ws->write("eof"));
$this->assertSame("eof", $ws->read());
$ws->close();
}

Expand All @@ -54,6 +56,12 @@ public function asynchronousOpenSendAndReceive()
$this->assertSame(6, $asyncWs->write("Worlds"));
sleep(1);
$this->assertSame("Worlds", $asyncWs->read(128));
$this->assertSame(3, $asyncWs->write("eof"));
$time = microtime(true) + 5.0;
while (!($message = $asyncWs->read()) && microtime(true) < $time) {
usleep(100);
}
$this->assertSame('eof', $message, 'Timed out while waiting for eof');
$asyncWs->close();
}
}

0 comments on commit 4ac84c6

Please sign in to comment.