swoole_client->on
最后更新于:2022-04-02 06:36:20
# swoole\_client->on
[TOC]
注册异步事件回调函数。
~~~
int swoole_client::on(string $event, mixed $callback);
~~~
* 参数`1`为事件类型,支持`connect/error/receive/close`4种
* 参数`2`为回调函数,可以是函数名字符串、匿名函数、类静态方法、对象方法。
* **同步阻塞客户端一定不要使用on方法**
> 调用`swoole_client->close()`时会自动退出事件循环
> `UDP`协议的`connect`事件在执行完`connect`方法后立即被回调`UDP`没有`close`事件
## 示例
~~~
$client = new swoole_client(SWOOLE_TCP | SWOOLE_ASYNC); //异步非阻塞
$client->on("connect", function($cli) {
$cli->send("hello world\n");
});
$client->on("receive", function($cli, $data) {
echo "received: $data\n";
sleep(1);
$cli->send("hello\n");
});
$client->on("close", function($cli){
echo "closed\n";
});
$client->on("error", function($cli){
exit("error\n");
});
$client->connect('127.0.0.1', 9501, 0.5);
~~~
';