我有一个带有高级模板的yii2项目,我希望使用mosquitto broker实现通知。我已经完成了发布部分和工作,现在我想在我的前端应用订阅一个主题的帮助。我已经试过了,但是当我订阅任何主题时,页面似乎停止工作了。有什么简单的方法或教程我可以使用吗?如果需要更多的信息,请询问。
P.S:我的想法是:当我在前端打开任何页面时,我检查消息,将它们保存在数组中,将它们设置为视图param,然后呈现我的页面。
编辑:到目前为止,我已经尝试了以下方法
班级
<?php
namespace common\models;
use Yii;
class Notificacoes
{
private $listaNotificacoes;
public function __construct($id, $name)
{
$this->listaNotificacoes = array();
$server = "127.0.0.1";
$port = 1883;
$username = "";
$password = "";
$client_id = $id;
$mqtt = new \common\mosquitto\phpMQTT($server, $port, $client_id);
if(!$mqtt->connect(true, NULL, $username, $password)) {
exit(1);
}
$topics[$name] = array("qos" => 0, "function" => "procmsg");
$mqtt->subscribe($topics, 0);
while($mqtt->proc()){
}
$mqtt->close();
}
function procmsg($topic, $msg)
{
\array_push($this->listaNotificacoes, $msg);
}
public function getAll()
{
return $this->listaNotificacoes;
}
}SiteController:我试图获取beforeAction方法上的消息
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
$notifications = array();
if (!Yii::$app->user->isGuest)
{
$notifs = new Notificacoes(Yii::$app->user->identity->getId(), Yii::$app->user->identity->username);
$notifications = $notifs->getAll();
}
$this->view->params['notifications'] = $notifications;
return true;
}发布于 2018-01-21 19:26:16
此模型不太可能工作,因为通常消息只在消息发布时由MQTT传递。
因此,除非您使用保留的消息或对给定客户端id的持久订阅来对消息进行队列处理。这意味着while循环将永远不会有任何消息要处理。
https://stackoverflow.com/questions/48368774
复制相似问题