html网页连接mqtt
时间: 2023-11-09 11:03:43 浏览: 110
要在HTML网页中连接MQTT,需要使用JavaScript和MQTT客户端库。以下是一个简单的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MQTT Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>
<script>
var client = new Paho.MQTT.Client("broker.mqtt.com", Number(8000), "clientId");
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.connect({onSuccess:onConnect});
function onConnect() {
console.log("Connected!");
client.subscribe("topic");
}
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("Connection lost: " + responseObject.errorMessage);
}
}
function onMessageArrived(message) {
console.log("Received message: " + message.payloadString);
}
function sendMessage() {
var message = document.getElementById("message").value;
var topic = document.getElementById("topic").value;
var payload = new Paho.MQTT.Message(message);
payload.destinationName = topic;
client.send(payload);
}
</script>
</head>
<body>
<input type="text" id="topic" placeholder="Topic">
<input type="text" id="message" placeholder="Message">
<button onclick="sendMessage()">Send</button>
</body>
</html>
```
在这个例子中,我们使用了Paho MQTT客户端库来连接到MQTT代理。我们创建了一个MQTT客户端对象,并在连接成功后订阅了一个主题。我们还定义了一些回调函数来处理连接丢失和接收到的消息。最后,我们创建了一个简单的表单来发送消息。
阅读全文