html mqtt 连接代码
时间: 2024-01-05 13:15:30 浏览: 176
以下是一个简单的HTML页面,使用JavaScript来连接MQTT服务器并订阅/发布主题的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>MQTT Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.1.0/paho-mqtt.min.js"></script>
</head>
<body>
<h1>MQTT Example</h1>
<div>
<label for="broker">MQTT Broker:</label>
<input type="text" id="broker" value="broker.example.com">
</div>
<div>
<label for="port">Port:</label>
<input type="number" id="port" value="1883">
</div>
<div>
<label for="topic">Topic:</label>
<input type="text" id="topic" value="example/topic">
</div>
<div>
<label for="message">Message:</label>
<input type="text" id="message" value="Hello, MQTT!">
</div>
<button onclick="connect()">Connect</button>
<button onclick="subscribe()">Subscribe</button>
<button onclick="publish()">Publish</button>
<script>
var client = null;
function connect() {
var broker = document.getElementById('broker').value;
var port = document.getElementById('port').value;
client = new Paho.MQTT.Client(broker, Number(port), "clientId");
client.connect({onSuccess:onConnect});
}
function onConnect() {
console.log("Connected");
}
function subscribe() {
var topic = document.getElementById('topic').value;
client.subscribe(topic);
client.onMessageArrived = onMessageArrived;
}
function onMessageArrived(message) {
console.log("Message received:", message.payloadString);
}
function publish() {
var topic = document.getElementById('topic').value;
var message = new Paho.MQTT.Message(document.getElementById('message').value);
message.destinationName = topic;
client.send(message);
}
</script>
</body>
</html>
```
请注意,此示例使用paho-mqtt JavaScript库,您需要在<head>标签中包含该库的链接,或者将其下载到本地并链接到您的HTML文件中。
在页面中,您需要填写MQTT代理服务器的主机名和端口号,以及要订阅/发布的主题和消息。单击Connect按钮将使用指定的代理服务器和端口号连接到MQTT服务器。单击Subscribe按钮将订阅指定的主题,并在消息到达时显示在控制台上。单击Publish按钮将发布指定的消息到指定的主题。
阅读全文