TCP/UDP Client

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

It is a wrapper of Linux TCP/UDP sockets client side API.

The client is blocking and sync can be used within PHP-FPM or simple client side CLI. It should not be used within coroutine context at server side.

TCP/UDP Client supports encrypted UDP DTLS.

Methods

Attributes

OpenSwoole\Client->errCode

When the call of method connect/send/recv/close failed, the value of OpenSwoole\Client->errCode is updated.

The value of OpenSwoole\Client->errCode equals to the value of errno of Linux.

You can use socket_strerror to check the details of an errCode.

<?php
echo socket_strerror($client->errCode);

OpenSwoole\Client->sock

It is an integer which stands for the file descriptor of socket.

You can use this value to convert a stream socket used for fread/fwrite/fclose functions.

<?php
$sock = fopen("php://fd/".$swoole_client->sock);

OpenSwoole\Client->reuse

If reuse the socket.

<?php
if ($client->reuse) {
    // reused socket
    $client->send($data);
} else {
    // new socket
    $client->doHandShake();
    $client->send($data);
}

OpenSwoole\Client->reuseCount

How many times the socket is reused.

OpenSwoole\Client->id

The client ID.

OpenSwoole\Client->settings

The full list of settings of the client.

Example

A simple sync TCP client:

<?php
use OpenSwoole\Client;

$client = new Client(OpenSwoole\Constant::SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1)) {
    exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("hello world\n");
echo $client->recv();
$client->close();
Last updated on September 20, 2022