swoole_client提供了tcp/udp socket的客戶端的封裝代碼,使用時僅需 new swoole_client即可。 swoole的socket client對比PHP提供的stream族函數(shù)有哪些好處:
除了普通的同步阻塞+select的使用方法外,swoole_client還支持異步非阻塞回調(diào)。
$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();
php-fpm/apache環(huán)境下只能使用同步客戶端
apache環(huán)境下僅支持prefork
多進(jìn)程模式,不支持prework
多線程
$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);
異步客戶端只能使用在cli命令行環(huán)境
更多建議: