简介
用来遍历当前Server所有的客户端连接,Server::getClientList方法是基于共享内存的,不存在IOWait,遍历的速度很快。另外getClientList会返回所有TCP连接,而不仅仅是当前Worker进程的TCP连接。
https://wiki.swoole.com/wiki/page/p-connection_list.html
实例代码
Server
<?php
class Server
{
private $serv;
public function __construct(){
$this->serv = new swoole_server('127.0.0.1', 9501);//注意这里要用多进程模式,不填写默认是多进程
$this->serv->set(array(
'worker_num' => 4,
'daemonize' => false,
'backlog' => 128,
));
$this -> query($this->serv);
$this->serv->on('Connect', array($this,'onConnect'));
$this->serv->on('Receive', array($this,'onReceive'));
$this->serv->on('Close', array($this,'onClose'));
$this->serv->start();
}
public function onConnect(swoole_server $server, int $fd, int $reactorId){
print_r($fd."--连接上了\n");
}
public function onReceive(swoole_server $server, int $fd, int $reactor_id, string $data){
print_r("主进程\n");
$start_fd = 0;
while(true)
{
$conn_list = $server->getClientList($start_fd, 10);
if ($conn_list===false or count($conn_list) === 0)
{
echo "finish\n";
break;
}
$start_fd = end($conn_list);//返回数组的最后一个元素的值
var_dump($conn_list);
foreach($conn_list as $fd)
{
$server->send($fd, "群发消息");
}
}
}
public function onClose(swoole_server $server, int $fd, int $reactorId){
print_r($fd."--关闭了连接\n");
}
function query($server) {
}
}
new Server();
Client
<?php
$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("task");
while (true) {
$as = $client->recv();
print_r($as."\n");
}