1.前面已经说过php服务器连接mqtt这里就不再赘述
1).数据库连接后进行数据处理,前端界面请求数据进行交互
下面这段代码是在服务器端后台自动运行,关闭不影响程序运行
nohup php /path/to/your/script.php > /dev/null 2>&1 &
use app\lyadmin\controller\phpMQTT;
// MQTT 服务器信息
require('phpMQTT.php');
$server = '43.138.37.240'; // 更改为你的 MQTT 服务器地址
$port = 1883; // 更改为你的 MQTT 服务器端口
$username = ''; // 设置你的 MQTT 服务器用户名
$password = ''; // 设置你的 MQTT 服务器密码
$client_id = 'phpMQTT-subscribe-msg'; // 保证该客户端 ID 在连接到服务器时是唯一的
$mqtt = new phpMQTT($server, $port, $client_id);
if (!$mqtt->connect(true, NULL, $username, $password)) {
exit(1);
}
while (true) {
$data = $mqtt->subscribeAndWaitForMessage('sub', 0); // 接收数据
$filePath = './data.txt';
// 删除文件
if (file_exists($filePath)) {
unlink($filePath);
}
$file = fopen($filePath, 'a');
// 将数据写入文件
fwrite($file, $data);
// 关闭文件
fclose($file);
}
2.html这样写
<!DOCTYPE html>
<html>
<head>
<title>MQTT 数据显示示例</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h1>MQTT 数据显示示例</h1>
<div id="data"></div>
//ajax请求
<script>
$.get("./data.txt",{},function (data){
$('#data').html(data);
console.log(data);
});
</script>
</body>
</html>