elk*_*nas 8 php session websocket symfony ratchet
我在使用Ratchet库的实时Symfony应用程序中工作,在这个应用程序中我需要将一些数据发送给特定用户,因此逻辑解决方案是使用SessionProvider将Symfony2 Session对象附加到每个传入的Connection对象.正如文档所述,我已经设置了一个非本地会话处理程序来存储我的会话,即通过PDO存储在数据库中.并且目前工作正常,但我需要获取特定用户的Connection对象以向他发送一些数据,所以在其他方面我需要找到引用此用户的连接对象,我找不到办法它?她是我的服务器代码:
$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();
Run Code Online (Sandbox Code Playgroud)
我自己也有完全相同的问题(减去Symfony),这就是我所做的.
基于hello world教程,我用一个数组替换了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();
}
}
Run Code Online (Sandbox Code Playgroud)
当然,为了使它真正有用,您可能还想添加数据库连接,并存储/检索这些resourceIds.
归档时间: |
|
查看次数: |
6626 次 |
最近记录: |