如何向特定用户发送消息Ratchet PHP Websocket

9 php real-time websocket ratchet

我正在尝试构建一个系统,用户可以在建立与websocket服务器的连接时订阅类别,然后他将开始接收该类别的更新.到目前为止,我已经与Ratchet合作,我能够向所有连接的客户端发送消息,但问题是我不想向所有客户端发送消息我只想将消息发送给订阅了该客户端的客户端.发送消息的特定类别.

PHP代码

Chat.php

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface
{
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
    }

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

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

server.php

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

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

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

$server->run();
?>
Run Code Online (Sandbox Code Playgroud)

客户端js代码

<script type="text/javascript">
var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function(e) {
  console.log("Connection established!");
};

conn.onmessage = function(e) {
  console.log(e.data);
};
</script>
Run Code Online (Sandbox Code Playgroud)

Mar*_*und 25

基本上你需要一个语法来发送数据到WebSocket,我建议使用JSON对象来做到这一点.在您的WebSocket类中,您需要一个名为subscriptions的局部变量和一个名为的局部变量users.

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface
{
    protected $clients;
    private $subscriptions;
    private $users;

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

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);
        switch ($data->command) {
            case "subscribe":
                $this->subscriptions[$conn->resourceId] = $data->channel;
                break;
            case "message":
                if (isset($this->subscriptions[$conn->resourceId])) {
                    $target = $this->subscriptions[$conn->resourceId];
                    foreach ($this->subscriptions as $id=>$channel) {
                        if ($channel == $target && $id != $conn->resourceId) {
                            $this->users[$id]->send($data->message);
                        }
                    }
                }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        unset($this->users[$conn->resourceId]);
        unset($this->subscriptions[$conn->resourceId]);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

与之相关的javascript看起来有点像这样

<script type="text/javascript">
var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function(e) {
  console.log("Connection established!");
};

conn.onmessage = function(e) {
  console.log(e.data);
};

function subscribe(channel) {
    conn.send(JSON.stringify({command: "subscribe", channel: channel}));
}

function sendMessage(msg) {
    conn.send(JSON.stringify({command: "message", message: msg}));
}
</script>
Run Code Online (Sandbox Code Playgroud)

注意:这段代码未经测试我是根据我对Ratchet的经验动态编写的.祝好运 :)


Anu*_*g K 6

好的,现在我分享我的经验。您可以发送令牌并将此令牌插入数据库中的onOpen(server.php)中。您可以在用户登录时插入聊天令牌。每次用户登录时都会生成并更新新的令牌。现在使用此令牌查找 onOpen 连接中的用户 ID。

var conn = new WebSocket('ws://172.16.23.26:8080?token=<?php echo !empty($_SESSION['user']['token']) ? $_SESSION['user']['token'] : ''; ?>');    
    conn.onopen = function(e) {
        console.log("Connection established!");
    };
Run Code Online (Sandbox Code Playgroud)

现在服务器.php

  public function onOpen(ConnectionInterface $conn) {
    $this->clients->attach($conn);      
    $querystring = $conn->httpRequest->getUri()->getQuery();
    parse_str($querystring,$queryarray);
   //Get UserID By Chat Token
    $objUser = new \users;
    $objUser->setLoginToken($queryarray['token']);
    $GetUserInfo = $objUser->getUserByToken();
    echo "New connection! ({$conn->resourceId})\n";
    //save Chat Connection
   // Insert the new connection with the user ID to Match to later if user ID in Table Then Update IT with a new connection 

 }
Run Code Online (Sandbox Code Playgroud)

现在您的连接已建立,然后向特定用户发送消息

客户端发送 USerID 以及收到的 ID 和消息

$("#conversation").on('click', '#ButtionID', function () {
         var userId      = $("#userId").val();
         var msg         = $("#msg").val();         
         var receiverId  = $("#receiverId").val();
      if ( userId  != null &&  msg  != null ){
        var data = {
            userId: userId,
            msg: msg,
            receiverId: receiverId
        };
        conn.send(JSON.stringify(data));
        $("#msg").val("");  
      }                 
    });
Run Code Online (Sandbox Code Playgroud)

服务器端

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');
      $data = json_decode($msg, true);
      echo $data['userId'];
      echo $data['msg'];
      echo $data['receiverId'];
     // Save User ID receiver Id message in table 
     //Now Get Chat Connection by user id By Table Which is saved onOpen function    
        $UptGetChatConnection   = $objChatroom->getChatConnectionUserID($data['receiverId']);
    $ReciId = $UptGetChatConnection[0]['ConnectionID'];
    foreach ($this->clients as $client) {
        if ($from == $client) {
           $data['from']  = "Me";
           $data['fromname'] = 5;
        } else {
           $data['from']  = $user['name'];
           $data['fromname'] = 6;
        }
        echo $client->resourceId;
        echo $ReciId."\n";
        if($client->resourceId == $ReciId || $from == $client){
            $client->send(json_encode($data));
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

现在消息已通过连接 ID 发送,不广播,仅发送特定用户