PHP WebSocket ZMQ - 聊天操作 - 向特定用户发送数据

2023-12-24

我正在开发一个基于 Symfony 2.2.11 的 PHP 项目,我安装了与以下教程相关的 socketohttp://socketo.me/docs/install http://socketo.me/docs/install使我的聊天脚本正常工作。

服务器命令.php// 启动WebSocket服务器的命令行代码

$oLoop = Factory::create();

    // Listen for the web server to make a ZeroMQ push after an ajax request
    $oContext = new Context($oLoop);
    $oPull = $oContext->getSocket(\ZMQ::SOCKET_PULL);
    // LET IT 127.0.0.1
    $oPull->bind('tcp://127.0.0.1:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
    $oPull->on('message', array($oChat, 'onMessage'));

    // Set up our WebSocket server for clients wanting real-time updates
    $oWebSock = new Server($oLoop);
    $oWebSock->listen(7979, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
    $webServer = new IoServer(
        new HttpServer(
            new WsServer(
                new WampServer(
                    $oChat
                )
            )
        ),
        $oWebSock
    );

    $oLoop->run();

将消息添加到数据库后:消息控制器.php

....
// This is our new stuff
        $oContext = new \ZMQContext();
        $oSocket = $oContext->getSocket(\ZMQ::SOCKET_PUSH, 'PushMe');
        $oSocket->connect("tcp://mydomain:5555");

        $aData = array(
            'topic'         => 'message',
            'sUsername'     => $oUserCurrent->getUsername(),
            'sMessage'      => $sMessage
        );

        $oSocket->send(json_encode($aData));
.....

聊天服务:Chat.php

/**
 * A lookup of all the topics clients have subscribed to
 */
public function onSubscribe(ConnectionInterface $conn, $topic) 
{
    // When a visitor subscribes to a topic link the Topic object in a  lookup array
    $subject = $topic->getId();
    $ip = $conn->remoteAddress;

    if (!array_key_exists($subject, $this->subscribedTopics)) 
    {
        $this->subscribedTopics[$subject] = $topic;
    }

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

    echo sprintf("New Connection: %s" . PHP_EOL, $conn->remoteAddress);

}

/**
 * @param string JSON'ified string we'll receive from ZeroMQ
 */
public function onMessage($jData) 
{
    $aData = json_decode($jData, true);

    var_dump($aData);

    if (!array_key_exists($aData['topic'], $this->subscribedTopics)) {
        return;
    }

    $topic = $this->subscribedTopics[$aData['topic']];

    // This sends out everything to multiple users, not what I want!!

    // re-send the data to all the clients subscribed to that category
    $topic->broadcast($aData);
}

接收数据的JS代码:messages.html.twig :

var conn = new ab.Session(
                    'ws://mydomain:7979' // The host (our Ratchet WebSocket server) to connect to
                  , function() {            // Once the connection has been established
                        conn.subscribe('message', function(topic, data) 
                        {
                            console.log(topic);
                            console.log(data);
                        });
                    }
                  , function() {            // When the connection is closed
                        console.warn('WebSocket connection closed');
                    }
                  , {                       // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
                        'skipSubprotocolCheck': true
                    }
                );

所以一切工作都很完美,当我发送一条新消息时,它会发送到数据库,然后到达聊天页面。

问题 :JS脚本在哪里,数据就落在哪里,结果是所有用户都可以获得相同的记录消息

ASKING :我怎样才能让数据落地特定用户 page ?

谢谢


您正在使用Ratchet在后端,对吗?

因此,这里有您需要的很好的案例示例:

http://socketo.me/docs/hello-world http://socketo.me/docs/hello-world

你应该把你的客户连接保留在里面$clients属性(不是资源 ID 的集合!)。因此,您可以从此集合中选择一个元素并仅向该客户端发送消息。

Example:

public function onSubscribe(ConnectionInterface $conn, $topic) 
{
    // When a visitor subscribes to a topic link the Topic object in a  lookup array
    $subject = $topic->getId();
    $ip = $conn->remoteAddress;

    if (!array_key_exists($subject, $this->subscribedTopics)) 
    {
        $this->subscribedTopics[$subject] = $topic;
    }

    $this->clients[] = $conn; // you add connection to the collection

    $conn->send("Hello new user!"); // you send a message only to this one user
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP WebSocket ZMQ - 聊天操作 - 向特定用户发送数据 的相关文章

随机推荐