Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

swoole为什么记不住客户端信息?

我的服务端代码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,交换对方的数据,服务器作为中间人,让两个客户端直接对话


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

看见$fd了吗?这就是服务端与客户端连接的描述符,你服务端从receive到一个$fd的数据,应该发送给另外一个$fd上,你现在发送给这个客户端本身,怎么能实现两个客户端的互通呢。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...