Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 22.x
Latest version:
pecl install openswoole-22.1.2
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.
Swoole\Client->__construct
Swoole\Client->set
Swoole\Client->connect
Swoole\Client->recv
Swoole\Client->send
Swoole\Client->sendfile
Swoole\Client->sendto
Swoole\Client->shutdown
Swoole\Client->enableSSL
Swoole\Client->getPeerCert
Swoole\Client->verifyPeerCert
Swoole\Client->isConnected
Swoole\Client->getsockname
Swoole\Client->getpeername
Swoole\Client->close
Swoole\Client->getSocket
Swoole\Client->errCode
When the call of method connect/send/recv/close
failed, the value of Swoole\Client->errCode
is updated.
The value of Swoole\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);
Swoole\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);
Swoole\Client->reuse
If reuse the socket.
<?php
if ($client->reuse) {
// reused socket
$client->send($data);
} else {
// new socket
$client->doHandShake();
$client->send($data);
}
Swoole\Client->reuseCount
How many times the socket is reused.
Swoole\Client->id
The client ID.
Swoole\Client->settings
The full list of settings of the client.
A simple sync TCP client:
<?php
use Swoole\Client;
$client = new Client(SWOOLE_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();