写一个网页的mqtt客户端的例子
时间: 2024-05-11 21:16:51 浏览: 43
好的,我可以为您提供一个基于JavaScript的MQTT客户端代码示例:
```
<!DOCTYPE html>
<html>
<head>
<title>MQTT Client Example</title>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js"></script>
</head>
<body>
<h1>MQTT Client Example</h1>
<form>
<label for="brokerInput">Broker URL:</label>
<input type="text" id="brokerInput" value="broker.mqtt.com">
<label for="portInput">Broker Port:</label>
<input type="number" id="portInput" value="1883">
<label for="clientIdInput">Client ID:</label>
<input type="text" id="clientIdInput" value="">
<label for="topicInput">Topic:</label>
<input type="text" id="topicInput" value="">
<label for="messageInput">Message:</label>
<input type="text" id="messageInput" value="">
<button type="button" onclick="connect()">Connect</button>
<button type="button" onclick="disconnect()">Disconnect</button>
<button type="button" onclick="publish()">Publish</button>
</form>
<script>
var client;
function connect() {
var brokerUrl = document.getElementById("brokerInput").value;
var brokerPort = document.getElementById("portInput").value;
var clientId = document.getElementById("clientIdInput").value;
client = new Paho.MQTT.Client(brokerUrl, Number(brokerPort), clientId);
client.connect({
onSuccess: onConnect,
onFailure: onFailure
});
}
function onConnect() {
alert("Connected to broker");
}
function onFailure(message) {
alert("Failed to connect to broker: " + message.errorMessage);
}
function disconnect() {
client.disconnect();
}
function publish() {
var topic = document.getElementById("topicInput").value;
var message = document.getElementById("messageInput").value;
var messageToSend = new Paho.MQTT.Message(message);
messageToSend.destinationName = topic;
client.send(messageToSend);
}
</script>
</body>
</html>
```
您可以在此基础上进行更改和扩展,以满足您的特定需求。
阅读全文