May 14, 2021 Swoole
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:
In addition to the normal use of sync blocking and select, swoole_client also supports asynchronous non-blocking callbacks.
$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 modeprefork
environment, andprework
is not supported
$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