保持MQTT客户端连接始终处于活动状态 [英] Keep a MQTT Client Connection always active

查看:1400
本文介绍了保持MQTT客户端连接始终处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基于Pub-Sub的应用程序中将CloudMQTT用作MQTT broker.我正在使用publisher通过topic将数据发布到CloudMQTT server,并且我打算subscribe分发到网页上的代理以接收传输的信息.

I am using CloudMQTT as a MQTT broker in my Pub-Sub based application. I am using my publisher to publish data to the CloudMQTT server over a topic, and I plan to subscribe to the broker on my webpage to recieve the transmitted information.

我正在使用此过程创建Client(订户): https://www .cloudmqtt.com/docs-php.html

I am using this procedure to create a Client(subscriber): https://www.cloudmqtt.com/docs-php.html

代码如下:

// subscribe.php
require("phpMQTT.php");

$host = "hostname"; 
$port = port;
$username = "username"; 
$password = "password"; 

$mqtt = new phpMQTT($host, $port, "ClientID".rand()); 

if(!$mqtt->connect(true,NULL,$username,$password)){
  exit(1);
}

//currently subscribed topics
$topics['topic'] = array("qos"=>0, "function"=>"procmsg");
$mqtt->subscribe($topics,0);

while($mqtt->proc()){        
}

$mqtt->close();
function procmsg($topic,$msg){
  echo "Msg Recieved: $msg";
}

这是phpMQTT.php文件: https://github.com/bluerhinos/phpMQTT/blob/master/phpMQTT.php

但是,在这种情况下,问题在于仅在打开网页时它才接收数据.即使网​​页未打开时我也要保持连接状态以始终接收已发布的消息,我该怎么办?

However, the issue in this case is that it recieves data only when the webpage is open.. I want to keep the connection alive even if the webpage is not open to always recieve published messages, how can I do it?

如果有人可以推荐一些替代方法,我可能会愿意使用服务器上的其他技术来处理此订阅过程

EDIT : I might be open to using some other technology on the server to handle this subscription process, if anyone can recommend some alternatives

推荐答案

PHP的典型操作模式是启动进程,等待HTTP连接,处理请求,然后启动新进程.这与具有长时间运行的流程的典型MQTT模式不太吻合.因此,当您关闭网页时,将关闭MQTT连接.

PHP's typically mode of operation is to start a process, wait for an HTTP connection, handle the request and then start a new process. This doesn't fit well with the typical MQTT mode of having a long-running process; hence closing the MQTT connection when you close the web page.

可以在长时间运行的CLI PHP脚本中订阅MQTT主题,但是您将必须具有其他某种机制来保持进程运行.有很多不同的方法可以执行此操作,具体取决于您的喜好和操作系统:

It is possible to subscribe to a MQTT topic in a long-running CLI PHP script, but you will have to have some other mechanism to keep the process running. There are a lot of different ways of doing this, depending on your preferences and operating system:

  • 在系统启动时使用/etc/rc.local启动的脚本
  • 使用init.d脚本
  • 使用流程管理器,例如DJB的daemontools或runit
  • 如果您使用的是Ubuntu,那么新贵是一种流行的机制

搜索stackoverflow会发现以下相关问题和几个答案:

Searching stackoverflow finds the following related question and several answers:

这篇关于保持MQTT客户端连接始终处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆