如何将下列红框部分改成不向所有设备发送,而是向发送信息的设备发送?

s898225836

如何将下列红框部分改成不向所有设备发送,而是向发送信息的设备发送?

$ws_worker = new Worker('Websocket://0.0.0.0:5656');
    // 这里只能写1
    $ws_worker->count = 1;
    // websocket server 启动后在当前进程增加一个socket监听
    $ws_worker->onWorkerStart = function($ws_worker)
    {
        // 增加一个Socket端口的监听设备发来的数据
        $socket_worker = new Worker('tcp://0.0.0.0:5555');
        // 当设备发来数据时如何处理
        $socket_worker->onMessage = function($connection, $data)
        {
            // 这里处理设备发来的数据 $data
            // 比如像这样给所有的WebSocket连接转发数据
_**         global $ws_worker;
            foreach($ws_worker->connections as $ws_con)
            {
               $ws_con->send($data);
            }**_
        };
        // 给ws_worker添加一个属性保存socket_worker,方便获取
        $ws_worker->socketWorker = $socket_worker;
        // 执行监听
        $socket_worker->listen();
    };
2157 1 0
1个回答

phpcreeper

关键是要建立抽象的uid 与 设备连接的映射关系,参考代码如下:

$worker = new Worker('text://0.0.0.0:3333');
$worker->count = 1;
$worker->onWorkerStart = function($worker){
    //开启一个内部端口,方便内部系统推送数据.
    $inner_text_worker = new Worker('text://0.0.0.0:4444');
    $inner_text_worker->onMessage = function($connection, $buffer)use ($worker) {
        global $worker;
        //$data数组里面有uid, 这样便于向特定uid推送数据: {"uid":2, "msg":"blogdaren"}
        $data = json_decode($buffer, true);
        $uid = $data;
        $msg = $data;

        //向特定uid推送数据
        $result = pushMessageByUid($uid, $msg);

        //返回推送结果
        $connection->send(true === $result ? 'success' : 'failed');
    };

    $inner_text_worker->listen();
};

//新增加一个属性,用来保存uid到connection的映射
$worker->uidConnections = array();

//最好通过onMessage回调来生产uid, 为了演示用onConnect回调.
$worker->onConnect = function($connection)use($worker) {
    //判断当前客户端是否已经验证
    if(!isset($connection->uid))
    {
        //为了演示, 简化将 $connection->id 用作uid
        $connection->uid = $connection->id;

        //保存uid到connection的映射,这样可以方便的通过uid查找connection, 实现针对特定uid推送数据
        $worker->uidConnections = $connection;

        return false;
    }
};

//当客户端连接断开时
$worker->onClose = function($connection)use($worker) {
    if(isset($connection->uid)) unset($worker->uidConnections);
};

//向特定uid推送数据
function pushMessageByUid($uid, $message)
{
    global $worker;

    if(isset($worker->uidConnections))
    {
        $connection = $worker->uidConnections;
        $connection->send($message);
        return true;
    }

    return false;
}

//运行所有的worker
Worker::runAll(); 
  • 暂无评论
年代过于久远,无法发表回答
×
🔝