通过套接字将消息发送到使用PHP Socket.IO的特定客户端

时间:2018-08-20 14:58:48

标签: php socket.io

我需要向连接到套接字服务器的客户端发送消息,但我只需要将消息发送给一个人,而不是广播。我已经读过了socket.IO的功能to()可以实现,但是我已经以几种方式实现了它,但是我没有得到,我将其发送给所有人。 这是我的代码

    ...
        $socket->on('new message', function($message) use($socket)
        {
            $socket->emit("new message", array(
                    "username" => $socket->username,
                    "action" => "me",
                    "message" => [ "from" => $socket->username['WP_USER_DATA']['guid'], "type" => "user", "time" => date('H:i'), "message" =>  $message ]
                )
            );
            //I NEED HELP HERE, PLEASE
            $socket->broadcast->emit("new message", array(
                "username" => $socket->username,
                "action" => "chat",
                "message" =>  [ "from" => $socket->username['WP_USER_DATA']['guid'], "type" => "", "time" => date('H:i'), "message" =>  $message ]
            ));
        });
    ...

1 个答案:

答案 0 :(得分:0)

来自Socket.IO cheatsheet

// sending to individual socketid (private message)
io.to(`${socketId}`).emit('hey', 'I just met you');

对您来说,就像:

//I NEED HELP HERE, PLEASE
io->to($socketId)->emit("new message", array(
    "username" => $socket->username,
    "action" => "chat",
    "message" =>  [ "from" => $socket->username['WP_USER_DATA']['guid'], "type" => "", "time" => date('H:i'), "message" =>  $message ]
));

注意:您需要在客户端连接时将其ID(array)存储在$socket->id中,并将您需要的ID用作{{1 }}。