@
@
@atambalasi2014-11-27 10:54:05
PHP
@atambalasi, 2014-11-27 10:54:05

How to send messages to only one client using php socket(Ratchet)?

I use the Ratchet library
and have a server

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Coreserver\Chat;

    require dirname(__DIR__) . '/vendor/autoload.php';

    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ),
        9300
    );

    $server->run();

Here is the Chat implementation
namespace Coreserver;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($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');
   

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
             
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $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();
    }

Now the server sends messages to everyone who has connected.
foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
             
            }
        }

I need to send only one client (whom to send to come from the client in json format
{
"from":"user1",
"toUser":"user2",
"message":"Hi"
}

).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BoneFletcher, 2014-11-27
@BoneFletcher

You need to match users and connections, this can be done, for example, by sending an authorization message {auth: "user1"}

protected $usersToClients = [];

public function onMessage(ConnectionInterface $from, $msg) {
    $msg = json_decode($msg);
    if (property_exists($msg, 'auth')) {
        $usersToClients[$msg->auth] = $from;
    } else {
        if (isset($usersToClients[$msg->toUser])) {
            $usersToClients[$msg->toUser]->send($msg->message);
        }
    }
}

P
Pianist, 2015-08-17
@kzakhariy

public function onMessage(ConnectionInterface $from, $msg) {
       foreach ($this->clients as $client) {
            if ($from === $client) {
                $client->send($msg);
            }
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question