Send message via socket to a specific client with PHP Socket.IO

0

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 ]
                )
            );
            //AQUI NECESITO AYUDA
            $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 ]
            ));
        });
    ...
    
asked by Anthony Medina 20.08.2018 в 17:00
source

1 answer

0

Currently my project runs with socket.io and php and the way I send personal messages in real time is with the data attribute of html, php sessions and a bit of logic.

If you are using php and socket io sessions it is necessary that you also emit the id of the user that you want to send that message to, to send it and read it in the way that I would it would be something like ...

the area where the message will be displayed, for example, in a div

//usamos la el atributo data de html para cojer el id del usuario

    <div class="recivir" id="recivir" data-message="<?php echo$_GET["id"]?>"></div>

then we make a condition in javascript to add the id of the user to whom we want to issue the message example

//emito el mensaje

    socket.emit("new message",{

                 message:message, //emitir mensaje
                 id: id //emitir id del usuario receptor

              });



//recivo el mensaje
    socket.on('new message', function(data){

          var actualuser = $(".recivir").attr(data-message);//el atributo data guardara agregamos el id de el usuario receptor

         //condicion que enviara el mensaje al usuario espesifico

         if(actualuser==data.id){

             actualuser.append(data.message)//aqui jugarias con lo que deceas agregar en el div

         }

               })

Currently you will find little material according to this topic, I say it from my own experience but investigate and solve my own problem.

you should know well how the data attribute of html work, there are many ways to do what you need but this is the one I manage best

    
answered by 20.08.2018 в 18:07