从棘轮Web套接字向客户端发送messege

时间:2017-12-12 16:19:05

标签: php websocket ratchet

我从这个tuts https://www.sitepoint.com/how-to-quickly-build-a-chat-app-with-ratchet/创建了一个Web套接字服务器 现在我想知道如何向特定连接发送消息。这些是我的代码。在这些代码中向所有连接发送消息,但我想知道哪个连接向我发送消息,然后向该连接发送消息。

我的客户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));
});
};
})();

和我的php服务器文件

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

1 个答案:

答案 0 :(得分:1)

我几天前也有类似的问题,我终于找到了一个很好的方法来处理好所有的连接:

而不是做

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

我将userId作为URL查询传递:

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

在服务器端,将userId和传入连接存储为PHP数组中的键值对。当您想要发送给特定用户时,只需索引该数组,即可获得连接。

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

如果您还希望限制每个用户一个连接,并且如果同一用户在其他地方登录,则通知旧连接,您可以在此处参考我的代码:

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