如何在Ratchet中处理单个客户端的多个套接字连接

时间:2018-09-24 20:18:25

标签: php laravel ratchet phpwebsocket ratchet-2

我正在开发一个实时聊天系统,其中一个用户可以向特定用户发送/接收消息。我正在使用Laravel,并且在控制器中我将连接对象映射到resourceId。

  

$ this-> connections [$ conn-> resourceId] = $ conn;

要查找特定用户的resource_Id,我将该用户的resource_Id与他的唯一ID相对应地保存在数据库中。这样,我可以找到用户的resource_Id及其unique_id,然后可以找到连接接口对象。

当user_1向user_2发送消息时,该user_2成功接收到此消息。

我怎么了?

假设user2打开一个标签,例如tab1并创建了一个连接,他成功接收到来自user_1的消息。 User_2打开另一个标签,然后创建一个新的连接,现在,如果他收到消息,它将仅出现在tab_2上,但我希望它同时出现在两个标签中。

我知道为什么它会出现在tab_2上,因为当创建第二个连接时,它会覆盖数据库中已经存在的resource_id,因为我仅针对每个用户存储一个resource_id。

是否可以通过相同的连接对象来处理两个选项卡。

我有解决办法。我想我必须针对一个user_id在数据库中存储多个资源ID,以便我可以访问特定用户的所有连接,然后向所有连接发送消息。就我而言,这是正确的方法吗?

这是控制器的onOpen函数的代码

    function onOpen(ConnectionInterface $conn){
    $this->connections[$conn->resourceId]=$conn;

    $data=['action'=>'map_resource_id','resourceid'=>($conn->resourceId)];
    //send the resource id to client to map this id against user_id
    //the client send an ajax request to store the resource id against 
    //user_id
    $conn->send(json_encode($data));

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

onClose方法的代码在这里

function onClose(ConnectionInterface $conn){
   unset($this->connections[$conn->resourceId]);
   $status=DB::update('update sockets set resource_id=0 where resource_id='.$conn->resourceId);

   echo "Connection {$conn->resourceId} has disconnected\n";

}

0 个答案:

没有答案
相关问题