<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://cdn.bootcss.com/paho-mqtt/1.0.2/mqttws31.min.js"></script>
<script>
client = new Paho.MQTT.Client("192.168.0.99", Number(61614), "websockets-test");//建立客户端实例
client.connect({onSuccess:onConnect});//连接服务器并注册连接成功处理事件
function onConnect() {
console.log("onConnected");
topic = 'smartroom'; //订阅的主题
client.subscribe(topic);//订阅主题
console.log("subscribed");
//发送消息
}
client.onConnectionLost = onConnectionLost;//注册连接断开处理事件
client.onMessageArrived = onMessageArrived;//注册消息接收处理事件
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
// console.log("onConnectionLost:"+responseObject.errorMessage);
console.log("连接已断开");
}
}
function onMessageArrived(message) {
console.log("收到消息:"+message.payloadString);
console.log("主题:"+message.destinationName);
}
</script>
</body>
</html>
网页端连接MQTT
最新推荐文章于 2024-09-26 14:11:18 发布
本文介绍了一个使用Paho MQTT库实现的简单MQTT客户端示例,该客户端能够连接到指定的MQTT服务器,订阅特定主题并接收消息。同时,示例展示了如何在连接成功、连接丢失及接收到消息时进行相应的处理。
摘要由CSDN通过智能技术生成