简体   繁体   中英

send messege to client from ratchet web socket

I create a web socket server from this tuts https://www.sitepoint.com/how-to-quickly-build-a-chat-app-with-ratchet/ now I want to know how can I send a message to the specific connection. these are my code. in these codes send a message to all connection but i want to know which connection send me a message then send a message to that connection.

my client js

(function(){

var user;
var messages = [];

function updateMessages(msg){
    messages.push(msg);
}

var conn = new WebSocket('ws://127.0.0.1:4510');
conn.onopen = function(e) {
console.log("Connection established!");
conn.onmessage = function(e) {
    var msg = JSON.parse(e.data);
    alert(msg);
    updateMessages(msg);
};
conn.onclose = function () {
    // conn.close();
}; // disable onclose handler first
var i = 0;
$('#start').click(function(){
    user = $('#user').val();
    var msg = {
    "name" : 'start' 
};
updateMessages(msg);
conn.send(JSON.stringify(msg));
});
};
})();

and my php server file

    <? 
protected $clients;
public $i = 0;
public function __construct() {
    $this->clients = new \SplObjectStorage;
}

public function onOpen(ConnectionInterface $conn) {

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

}

public function onMessage(ConnectionInterface $from, $msg) {

        foreach ($this->clients as $client) {
            if ($from !== $client) {

                $client->send($rsid);
            }
        }

}

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();
}

I have the similar issue days ago, and I finally find a good way to handle all the connections in a good way:

Instead of doing

var conn = new WebSocket('ws://127.0.0.1:4510');

I pass the userId as an URL query like that:

var conn = new WebSocket('ws://127.0.0.1:4510/?id=123');

On the server-side, store the userId and incoming connection as a key-value pair in PHP array. When you want to send to specific user, just index that array and you will get the connection.

        $query = $conn->httpRequest->getUri()->getQuery();
        //get query from URL like ws://127.0.0.1:8080/?id=123456
        $query_list = explode("&", $query);
        $user_id = trim(substr($query_list[0], 3));
        $this->users[$user_id] = $conn;

If you also want to limit one connection per user and notify the old connection if the same user login elsewhere, you can refer to my code here:

https://github.com/tli4/ratchet-practice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM