Ratchet PHP Websockets:私人消息传递(控制消息发送给谁)

emj*_*jay 1 javascript php jquery websocket ratchet

还有一个问题。我开始习惯 websocket 的工作方式。我什至设法实现了跨域通信。但现在我还没有达到另一个里程碑。

这是我当前实现的一个片段

 public function onMessage(ConnectionInterface $conn, $msg)
{
     $msgjson = json_decode($msg);
     $tag = $msgjson->tag;
     global $users; 

     if($tag == "[msgsend]")
     {

            foreach($this->clients as $client)
            {
                  $client->send($msg);    
            }
     }
     else if($tag == "[bye]")
     {

         foreach($this->clients as $client)
         {
              $client->send($msg);    
         }

         foreach($users as $key => $user)
         {
             if($user->name == $msgjson->uname)
             {
                unset($users[$key]); 
             }
         }

         $this->clients->detach($conn);
     }
     else if($tag == "[connected]")
     {
         //store client information
         $temp = new Users();
         $temp->name = $msgjson->uname;
         $temp->connection = $conn;
         $temp->timestamp = new \DateTime();



         $users[] = $temp;





          usort($users, array($this, "cmp"));


         //send out messages
          foreach($this->clients as $client)
         {
              $client->send($msg);    
         }           

     }
     else if($tag == "[imalive]")
     {
         //update user timestamp who sent [imalive]
         global $users;

          foreach($users as $user)
             {
                if($msgjson->uname == $user->name)
                {
                        $user->timestamp = new \DateTime(); 
                }
             }

     }   

}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是。正如我们所看到的,在 onMessage() 函数和我完成的教程中,我知道如何读取和解析 JSON 数据,理解消息,告诉谁消息来自 ($conn).....

但是,当我在 JSON 数据包中发送消息时,我想包括消息来自谁以及消息将要发送给谁的昵称。这将允许我在我正在构建的社交网络和聊天室中实施私人即时消息传递。

而不是 for 循环向所有连接的客户端发送消息,我只想向特定的客户端发送消息。我知道客户有一个属性($this->$client->resourceID 或类似的东西),但不确定如何将其合并为解决方案。我还希望用户在跳转到网站上的不同页面时保持连接,即使在刷新后,仍然能够继续发送消息。我假设每次刷新都会断开客户端的连接。所以我必须有一种方法让服务器每次都可以告诉谁是谁,消息来自哪里以及他们要去哪里。

但是,是的,私人消息。我不想向所有人或非预期目标发送不必要的信息。我怎样才能做到这一点?我希望我的问题是有道理的。谢谢。

She*_*rif 7

能够唯一地识别连接到您的 WebSocket 服务器的用户,然后能够定位这些用户,特别是,当发送消息时,需要从onOpen与服务器实际协商连接的回调开始。

在您的onOpen方法中,您应该有某种方式通过一些全局存储在您的数据库或持久性存储中的用户 ID 来唯一标识系统上的用户。由于连接是通过 HTTP 协商的,因此您可以通过 访问 HTTP 请求$conn->WebSocket->request,它是一个GuzzleHttp包含客户端 HTTP 请求信息的对象。例如,您可以使用它来拉取一个 cookie,其中包含一些用户 ID 数据或令牌,您可以将它们与您的数据库进行比较,以确定用户是谁,然后将其存储为$client对象的属性。

现在,让我们假设您正在编写一个普通的 PHP 脚本,在该脚本中您通过 HTTP 进行用户身份验证并将用户 ID 存储在会话中。此会话在客户端机器上设置一个包含会话 ID的 cookiePHPSESSID默认情况下,cookie 名称是会话名称,除非您更改它,否则通常为该名称)。此会话 ID 可用于您的 WebSocket 服务器,以与您通常在 PHP 中所做的相同的方式访问会话存储。

这是一个简单的示例,我们期望PHPSESSID从请求中命名的 cookie从 cookie 中捕获会话 ID。

public function onOpen(ConnectionInterface $conn) {
    // extract the cookie header from the HTTP request as a string
    $cookies = (string) $conn->WebSocket->request->getHeader('Cookie');
    // look at each cookie to find the one you expect
    $cookies = array_map('trim', explode(';', $cookies));
    $sessionId = null;
    foreach($cookies as $cookie) {
        // If the string is empty keep going
        if (!strlen($cookie)) {
            continue;
        }
        // Otherwise, let's get the cookie name and value
        list($cookieName, $cookieValue) = explode('=', $cookie, 2) + [null, null];
        // If either are empty, something went wrong, we'll fail silently here
        if (!strlen($cookieName) || !strlen($cookieValue)) {
            continue;
        }
        // If it's not the cookie we're looking for keep going
        if ($cookieName !== "PHPSESSID") {
            continue;
        }
        // If we've gotten this far we have the session id
        $sessionId = urldecode($cookieValue);
        break;
    }
    // If we got here and $sessionId is still null, then the user isn't logged in
    if (!$sessionId) {
        return $conn->close(); // close the connection - no session!
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您实际上拥有了$sessionId可以使用它来访问该会话的会话存储,将会话信息拉入您的 WebSocket 服务器并将其存储为客户端连接对象的属性$conn

因此,继续上面的示例,让我们将此代码添加到onOpen方法中。

public function onOpen(ConnectionInterface $conn) {
    $conn->session = $this->methodToGetSessionData($sessionId);
    // now you have access to things in the session
    $this->clinets[] = $conn;
}
Run Code Online (Sandbox Code Playgroud)

现在,让我们回到您想要专门向一个用户发送消息的示例。假设我们在会话中存储了以下属性,现在可以从客户端连接对象访问这些属性...

$conn->session->userName = 'Bob';
$conn->session->userId   = 1;
Run Code Online (Sandbox Code Playgroud)

因此,假设 Bob 想向 Jane 发送消息。请求进入您的 WS 服务器,{"from":1,"to":2,tag:"[msgsend]"}其中JSON的tofrom属性基本上分别是消息来自的用户的用户 ID和消息要发送的用户的用户 ID 。让我们假设 Jane 是userId = 2这个例子。

public function onMessage(ConnectionInterface $conn, $msg) {
    $msgjson = json_decode($msg);
    $tag = $msgjson->tag;
    if ($tag == '[msgsend]') {
        foreach($this->clients as $client) {
            // only send to the designated recipient user id
            if ($msgjson->to == $client->session->userId) {
                $client->send($msg);    
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,您可能希望在那里进行更详细的验证,但您应该能够从这里扩展这一点。

  • $conn->WebSocket->request->getHeader('Cookie'); 现在更改为 $conn->httpRequest->getHeader('Cookie'); 在新的棘轮上 (3认同)