dpj83664 2016-10-24 15:05
浏览 1339
已采纳

保持MQTT客户端连接始终处于活动状态

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.

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

Code goes as follows:

// 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";
}

Here is the phpMQTT.php file: 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

  • 写回答

1条回答 默认 最新

  • doujia3441 2016-10-24 15:38
    关注

    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.

    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:

    • a script started using /etc/rc.local at system startup
    • using a init.d script
    • using a process manager, such as DJB's daemontools or runit
    • If you are using Ubuntu, then upstart is a popular mechanism

    Searching stackoverflow finds the following related question and several answers:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python动态规划:N根火柴摆出的最大数字
  • ¥20 (标签-excel)
  • ¥200 求idea10和MyEclipse7.1
  • ¥20 vb6.0截取当前窗体保存为jpg文件
  • ¥20 苹果手机不使用大疆sdk怎么获取遥控器控制信息或如何接入大疆sdk并且成功上架sdk
  • ¥20 woocommerce 注册按键重定向
  • ¥100 求书法图像文字切割代码
  • ¥15 同一个波形探测距离不同的目标,为什么fft之后得到的频谱图会发生移动,不应该时移不改变幅度谱吗(标签-matlab)(相关搜索:matlab仿真)
  • ¥15 Proteus仿真程序只能执行一次
  • ¥15 语音识别websocket报错