网页端HTML使用MQTTJs订阅RabbitMQ数据
要在HTML页面中使用MQTT.js订阅RabbitMQ的数据,你需要首先引入MQTT.js库,并确保RabbitMQ服务器允许你的客户端连接。以下是一个简单的例子:
<!DOCTYPE html>
<html>
<head>
<title>MQTT Subscribe Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqtt.min.js"></script>
<script>
var client;
function connect() {
var host = 'wss://your-rabbitmq-server:port/ws'; // 使用WebSocket连接
client = new Paho.MQTT.Client(host, "your-client-id");
var options = {
timeout: 3,
keepAliveInterval: 30,
cleanSession: true,
useSSL: true,
userName: 'your-username', // 如果RabbitMQ配置了用户名和密码,则需要
password: 'your-password',
onSuccess: onConnect,
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
};
client.connect(options);
}
function onConnect() {
console.log("Connected");
client.subscribe('your-topic'); // 你要订阅的主题
}
function onFailure(message) {
console.log("Failed to subscribe: " + message.errorMessage);
}
function receiveMessage() {
client.onMessageArrived = function (message) {
console.log("Message arrived: " + message.payloadString);
// 处理接收到的消息
};
}
// 页面加载完成后连接MQTT
window.onload = function() {
connect();
receiveMessage();
};
</script>
</head>
<body>
<h1>MQTT Subscribe Example</h1>
</body>
</html>
确保替换以下内容:
your-rabbitmq-server:port/ws
:为你的RabbitMQ服务器的WebSocket端点。your-client-id
:为你的客户端ID,需要是唯一的。your-username
和your-password
:如果RabbitMQ设置了用户名和密码,则需要这些信息。your-topic
:你要订阅的具体主题。
在实际部署时,请确保你的RabbitMQ服务器允许来自你客户端IP的WebSocket连接,并且正确配置了用户名和密码(如果有的话)。
评论已关闭