发布于 2015-08-09 09:40:56 | 830 次阅读 | 评论: 0 | 来源: 网络整理
swoole_client提供了tcp/udp socket的客户端的封装代码,使用时仅需 new swoole_client即可。 swoole的socket client对比PHP提供的stream族函数有哪些好处:
除了普通的同步阻塞+select的使用方法外,swoole_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 worldn");
echo $client->recv();
$client->close();
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(swoole_client $cli) {
$cli->send("GET / HTTP/1.1rnrn");
});
$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 "errorn";
});
$client->on("close", function(swoole_client $cli){
echo "Connection closen";
});
$client->connect('127.0.0.1', 9501);