Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Coroutine\Client->peek(int $length = 65535): string
The total length of data to read, in bytes.
Returns false
if there is no data to be returned from the buffer, if there is content to be read from the cache, then the data is returned as a string. See description for more details.
The peek method is used to read only part of the data, you can specify how much using the $length
parameter.
When calling this method, it is non-blocking, it returns immediately, you can use recv()
to still read the same data, However, calling peek allows you to read data directly from the kernel socket cache buffer, when the buffer has data it will return it immediately, if it doesn't false
is returned to indicate no data is currently available in the buffer. An empty string is returned when the connection has been closed.
Calling this method does not cause coroutines to be switched/scheduled as this method returns immediately.
<?php
use OpenSwoole\Coroutine\Client;
co::run(function()
{
$client = new Client(OpenSwoole\Constant::SOCK_TCP);
if(!$client->connect('127.0.0.1', 9501, 0.5))
{
echo "Connection failed with error: {$client->errCode}\n";
}
// Should not rely on this 100%, see description as to why
if($client->isConnected() === false)
{
echo "Connection failed with error: {$client->errCode}\n";
}
$client->send("Hello World! - from OpenSwoole\n");
if($data = $client->peek())
{
var_dump($data);
}
echo $client->recv();
$client->close();
});