直接上代码:
<?php
class MyClient
{
private $cli;
private $ip;
private $port;
public function __construct($ip, $port)
{
$this->ip = $ip;//请求地址
$this->port = $port;//端口号
$this->cli = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);//异步非阻塞
$this->cli->on('connect', array($this, 'onConnect'));
$this->cli->on('receive', array($this, 'onReceive'));
$this->cli->on('error', array($this, 'onError'));
$this->cli->on('close', array($this, 'onClose'));
$this->cli->connect($this->ip, $this->port);
}
public function onConnect()
{
echo "success:".$this->ip."\n";
}
public function onReceive()
{
echo "Receive:".$this->ip."\n";
}
public function onError()
{
echo "error\n";
}
public function onClose()
{
echo "Connection close:".$this->ip."\n";
}
}
$C1 = new MyClient('127.0.0.1', 9501);
新建一个异步非阻塞客户端,可以提高访问服务器的效率,无需等待某个服务器回应再去请求下一个。例如多数据库请求。在同步情况下:
请求3个数据库的时间=A+B+C
而在异步情况下:
请求3个数据库的时间≈max(A,B,C)
PS:异步客户端只能在命令行模式下运行。

597

被折叠的 条评论
为什么被折叠?



