0
votes

I need to send a message to a client connected to a socket server but I need it to only be sent to a person, and not a broadcast as such. I have read that with the function to() of socket.IO it can be but I have implemented it in several ways and I do not get it, I send it to all. this is my code

    ...
        $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

1 Answers

0
votes

From the Socket.IO cheatsheet:

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

So for you, it's something like:

//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 ]
));

Note: you need to store (in array) the ids ($socket->id) of the clients when they connected, and use the one you need as $socketId in the example above.