Swoole\Coroutine\Client->send(...)

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\Coroutine\Client->send(string $data): int|bool

Parameters

data

The data to send to the connected remote server. Must be a string type and support binary data.

Return

A successful send will return the number of bytes that were sent. A failed send will return false, you should then use $client->errCode to find out why.

Description

Send a TCP/UDP package to the connected remote server. Data can be either string or binary.

When a successful send starts to happen, sometimes the $data may be differing lengths upon the return compared to the actual full $data length, this is because the socket failed during the data transfer and the socket has been closed resulting in a send which returns how many bytes were managed to be sent, you should then check the error code using $client->errCode.

Example

<?php
use Swoole\Coroutine\Client;

Co\run(function()
{
    $client = new Client(SWOOLE_SOCK_TCP);

    if(!$client->connect('127.0.0.1', 9501, 0.5))
    {
        echo "Connection failed with error: {$client->errCode}\n";
    }

    $data = "Hello World! - from Swoole\n";

    $result = $client->send($data);

    if($result === false || $result !== strlen($data))
    {
      echo "Failed to correctly send data, error code: $client->errCode\n";
    }

    echo $client->recv();

    $client->close();
});
Last updated on August 31, 2022