Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swoole Client instance


May 14, 2021 Swoole


Table of contents


Introduction to Swoole Client

swoole_client provides the encapsulation code for the tcp/udp socket client, which requires only a new swoole_client use. Swoole's socket client compares the benefits of PHP's stream family functions:

  • The stream function has traps and bugs set by timeouts that, if not handled, can cause long-term blocking on the server side
  • The fread has an 8192 length limit and cannot support large UDP packages
  • swoole_client support waitall, which can be picked up at once without having to cycle through the length of the package.
  • swoole_client UDP connect is supported to solve the UDP packet problem
  • swoole_client is pure C code, specializing in socket, stream function is very complex. swoole_client performance is better

In addition to the normal use of sync blocking and select, swoole_client also supports asynchronous non-blocking callbacks.

Synchronized blocking clients

$client = new swoole_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();

Only sync clients can be used in php-fpm/apache environments
Prefork multi-process mode prefork environment, and prework is not supported

Asynchronous non-blocking clients

$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");
    sleep(1);
});
$client->on("error", function(swoole_client $cli){
    echo "error\n";
});
$client->on("close", function(swoole_client $cli){
    echo "Connection close\n";
});
$client->connect('127.0.0.1', 9501);

Asynchronous clients can only be used in cli command-line environments