Skip to content
This repository has been archived by the owner on Sep 1, 2020. It is now read-only.

Latest commit

 

History

History
51 lines (46 loc) · 1.67 KB

12 - Client.md

File metadata and controls

51 lines (46 loc) · 1.67 KB

Client

Client提供了TCP/UDP socket的客户端的封装代码,使用时仅需 new Swoole\Client 即可。

优势

  • stream函数存在超时设置的陷阱和Bug,一旦没处理好会导致Server端长时间阻塞
  • stream函数的fread默认最大8192长度限制,无法支持UDP的大包
  • Client支持waitall,在有确定包长度时可一次取完,不必循环读取
  • Client支持UDP connect,解决了UDP串包问题
  • Client是纯C的代码,专门处理socketstream函数非常复杂。Client性能更好
  • Client支持长连接

除了普通的同步阻塞+select的使用方法外,Client还支持异步非阻塞回调。

同步阻塞客户端

$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环境下只能使用同步客户端
apache环境下仅支持prefork多进程模式,不支持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命令行环境