Swoole Client for TCP/UDP

Use the corotuine version within Coroutine context: Swoole\Coroutine\Client

Swoole client provide the wrapper of TCP/UDP sockets client side API.

Compare with PHP stream functions, Swoole\Client is more advanced:

  • There is a bug in stream function,
  • fread has the limitation length of 8129, can't support big UDP packet
  • Swoole\Client supports waitall, able to read all the data if the packet length is known.
  • Swoole\Client supports UDP connect, there will be no UDP packets mixing up issues.
  • Swoole\Client has better performance.
  • Swoole\Client supports async non-blocking callback, along with sync blocking and select API.

Table of Contents


A simple sync TCP client:

$client = new Swoole\Client(SWOOLE_SOCK_TCP);
if (!$client->connect('', 9501, -1))
    exit("connect failed. Error: {$client->errCode}\n");
$client->send("hello world\n");
echo $client->recv();

A simple async TCP client:

$client = new Swoole\Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(Swoole\Client $cli) {
    $cli->send("GET / HTTP/1.1\r\n\r\n");
$client->on("receive", function(Swoole\Client $cli, $data){
    echo "Receive: $data";
    $cli->send(str_repeat('A', 100)."\n");
$client->on("error", function(Swoole\Client $cli){
    echo "error\n";
$client->on("close", function(Swoole\Client $cli){
    echo "Connection close\n";
$client->connect('', 9501);

Note, the async TCP client can not be used in PHP-FPM or Apache mode, only can be used in Swoole server.