L
L
Luigi2021-10-20 12:01:23
PHP
Luigi, 2021-10-20 12:01:23

How to send a message to a specific Ratchet user?

I am developing a chat platform.
As a server part, I use Laravel + the Ratchet library for working with sockets.

When the user opens the chat, a socket connection is established. However, when the interlocutor writes a message in the chat, it is sent to everyone else, and not to a specific second interlocutor in the chat. (IMPORTANT: Chat is 1 on 1 only)

I've read a lot of tutorials and looked at a lot of examples, but I still don't understand how do I send a message to a specific user?
I will save the connection id in a separate users array, but I can’t figure out how to select the user I need from there.

It is worth noting that messages are received correctly in the database, they are assigned to the necessary chat rooms.
Here is the mod chat class:

class ChatSocket extends BaseSocket
{
    protected $clients;
    protected $users;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage();
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg)
    {
        $numRecv = count($this->clients) - 1;

        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        $data = json_decode($msg, true, 512, JSON_THROW_ON_ERROR);

//        Save to Database
        $message = new MessageController();
        $responseData = $message->store($data);

        foreach ($this->clients as $client) {
            if ($client === $from) {
                $client->send(json_encode($responseData, JSON_THROW_ON_ERROR));
            }
        }
    }



    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }


Here is the client code (very clumsy, I send user IDs as id (taken from the database).

form.addEventListener('submit', function (e) {
            e.preventDefault();
            
            let data = {
                sender_id: 1,
                to: 2,
                chat_room_id: 1,
                message: this.message.value
            };

            socket.send(JSON.stringify(data));

        })

        socket.onmessage = function(event) {
            let data = JSON.parse(event.data);
            console.log(data);
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question