简介
connect会立即返回true。但实际上连接并未建立。所以不能在connect后使用send。通过isConnected()判断也是false。当连接成功后,系统会自动回调onConnect。这时才可以使用send向服务器发送数据。
https://wiki.swoole.com/wiki/page/30.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,
'dispatch_mode' => 5,
));
$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
class Client
{
private $client;
private $sendData;
public function __construct()
{
$this->client = new swoole_client(SWOOLE_SOCK_TCP,SWOOLE_SOCK_ASYNC);
$this->initOn();
if (!$this->client->connect('127.0.0.1', 9501, -1))
{
return false;
}
}
public function setSendData(string $data):void
{
$this->sendData=$data;
}
public function initOn(){
$this->client->on("connect",array($this,"onConnect"));
$this->client->on("error",array($this,"onError"));
$this->client->on("close",array($this,"onClose"));
$this->client->on("receive",array($this,"onReceive"));
}
public function onConnect(swoole_client $client){
print_r("客户端:我连接上了");
$client->send($this->sendData);
}
public function onError(swoole_client $client){
echo "Client is error";
}
public function onClose(swoole_client $client){
echo "客户端关闭了连接";
}
public function onReceive(swoole_client $client, string $data){
if(empty($data)){
$client->close();
echo "closed\n";
} else {
echo "received: $data\n";
sleep(1);
$client->send("hello\n");
}
}
}
Main
<?php
require_once "Client.php";
$Client = new Client();
$Client->setSendData("我是客户端发送的数据");