gpt4 book ai didi

php - 如何获取特定用户的连接对象?

转载 作者:可可西里 更新时间:2023-11-01 12:33:35 26 4
gpt4 key购买 nike

我正在使用 Ratchet 库在实时 Symfony 应用程序中工作,在这个应用程序中我需要向特定用户发送一些数据,因此逻辑解决方案是使用SessionProvider 会将 Symfony2 Session 对象附加到每个传入的 Connection 对象。正如文档所述,我已经设置了一个非本地 session 处理程序来存储我的 session ,即通过 PDO 在数据库中。并且目前工作正常但我需要让特定用户的连接对象向他发送一些数据所以以其他方式我需要找到引用该用户的连接对象但我找不到方法它 ?她是我的服务器代码:

    $app=new AggregateApplication();
$loop = \React\EventLoop\Factory::create();
$context = new \React\ZMQ\Context($loop);
$pull = $context->getSocket(\ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5555');
$pull->on('message', array($app, 'onNotification'));
$webSock = new \React\Socket\Server($loop);
$webSock->listen(8080, '127.0.0.1');
$handler = $this->getContainer()->get('session.handler');
$server=new \Ratchet\Wamp\WampServer($app);
$server = new SessionProvider($server, $handler);
$webServer = new \Ratchet\Server\IoServer(new \Ratchet\WebSocket\WsServer($server),$webSock);
$loop->run();

最佳答案

我自己也有同样的问题(除了 Symfony),这就是我所做的。

基于hello world tutorial ,我用数组替换了 SplObjectStorage。在介绍我的修改之前,我想评论一下,如果您按照该教程进行操作并理解它,那么唯一阻止您自己获得此解决方案的可能是不知道什么 SplObjectStorage是。

class Chat implements MessageComponentInterface {
protected $clients;

public function __construct() {
$this->clients = array();
}

public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients[$conn->resourceId] = $conn;
echo "New connection! ({$conn->resourceId})\n";
}

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');

foreach ($this->clients as $key => $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
// Send a message to a known resourceId (in this example the sender)
$client = $this->clients[$from->resourceId];
$client->send("Message successfully sent to $numRecv users.");
}

public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
unset($this->clients[$conn->resourceId]);

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

public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";

$conn->close();
}
}

当然,为了让它真正有用,您可能还想添加一个数据库连接,并存储/检索那些 resourceIds。

关于php - 如何获取特定用户的连接对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com