我的服务端代码s.php
<?php
$clientList=array();
$serv = new SwooleServer("127.0.0.1", 9501);
$serv->set(array(
'worker_num' => 1, //工作进程数量
'daemonize' => false, //是否作为守护进程
));
$serv->on('connect', function ($serv, $fd){
echo "Client:Connect.
";
});
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
$json = json_decode($data, true);
if(isset($json['clientId'])){
$clientList[$json['from']][$json['clientId']] = $fd;
print_r($clientList);
}
$serv->send($fd, 'Swoole: '.$data);
//$serv->close($fd);
});
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.
";
});
$serv->start();
?>
客户端c1.php
<?php
$client = new SwooleClient(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
//设置事件回调函数
$client->on("connect", function($cli) {
$cli->send('{"clientId":"4c2c","from":"c1"}');
while(1){
sleep(3);
$cli->send('{"data":"c1"}');
}
});
$client->on("receive", function($cli, $data){
echo "Received: ".$data."
";
});
$client->on("error", function($cli){
echo "Connect failed
";
});
$client->on("close", function($cli){
echo "Connection close
";
});
//发起网络连接
$client->connect('127.0.0.1', 9501, 0.5);
?>
客户端c2.php
<?php
$client = new SwooleClient(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
//设置事件回调函数
$client->on("connect", function($cli) {
$cli->send('{"clientId":"4c2c","from":"c2"}');
while(1){
sleep(3);
$cli->send('{"data":"c2"}');
}
});
$client->on("receive", function($cli, $data){
echo "Received: ".$data."
";
});
$client->on("error", function($cli){
echo "Connect failed
";
});
$client->on("close", function($cli){
echo "Connection close
";
});
//发起网络连接
$client->connect('127.0.0.1', 9501, 0.5);
?>
为什么服务端最后是
Array
(
[c2] => Array
(
[4c2c] => 2
)
)
我想实现的是根据clientId记住两个客户端是一组,根据from,交换对方的数据,服务器作为中间人,让两个客户端直接对话
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…