<body>
<meta charset="utf-8">
<input id="_message" width="300px" height="200px">
<button id="_sendBtn">发送消息</button>
<div id="div1"></div><br>
<div id="div2"></div><br>
<div id="div3"></div><br>
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js" ></script>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js" ></script>
<script src="https://cdn.bootcdn.net/ajax/libs/mqtt/4.1.0/mqtt.min.js" ></script>
<script type="text/javascript">
$(function () {
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'client_id',
username: "web-html",
password: 'no'
}
const connectUrl = 'ws://qwtz.net:8083/mqtt'
const client = mqtt.connect(connectUrl, options);
//当重新连接启动触发回调
client.on('reconnect', () => {
$("#div1").text("正在重连.....");
});
//连接断开后触发的回调
client.on("close",function () {
$("#div1").text("客户端已断开连接.....");
});
//从broker接收到断开连接的数据包后发出。MQTT 5.0特性
client.on("disconnect",function (packet) {
console.log("从broker接收到断开连接的数据包....."+packet);
});
//客户端脱机下线触发回调
client.on("offline",function () {
$("#div1").text("客户端脱机下线.....");
});
//当客户端无法连接或出现错误时触发回调
client.on("error",(error) =>{
$("#div1").text("客户端出现错误....."+error);
});
//当客户端发送任何数据包时发出。这包括published()包以及MQTT用于管理订阅和连接的包
client.on("packetsend",(packet)=>{
/**
* packet包数据格式
*
* cmd: "publish"
* dup: false
* messageId: 18467
* payload: "111"
* qos: 2
* retain: false
* topic: "/tra_topic"
*/
console.log("客户端已发出数据包....."+packet.payload);
});
//当客户端接收到任何数据包时发出。这包括来自订阅主题的信息包以及MQTT用于管理订阅和连接的信息包
client.on("packetreceive",(packet)=>{
console.log(packet);
});
//成功连接后触发的回调
client.on("connect",function (connack) {
$("#div1").text("成功连接上服务器"+new Date());
/**
* 订阅某主题
* client.subscribe(topic/topic array/topic object, [options], [callback])
* topic:一个string类型的topic或者一个topic数组,也可以是一个对象
* options
*/
client.subscribe("/dht/#",{qos:2});
});
$("#_sendBtn").on('click',function () {
//发布数据
var message = $("#_message").val();
if (message==''){
alert("请输入发送内容");
return;
}
client.publish("/dht/1",message,{qos:2});
$("#div2").text("发送成功");
$("#_message").val("");
})
//当客户端接收到发布消息时触发回调
/**
* topic:收到的数据包的topic
* message:收到的数据包的负载playload
* packet:收到的数据包
*/
client.on('message', (topic, message,packet) => {
$("#div3").text("客户端收到订阅消息,topic="+topic+";消息数据:"+message+";数据包:"+packet);
});
//页面离开自动断开连接
$(window).bind("beforeunload",()=>{
$("#div1").text("客户端窗口关闭,断开连接");
client.disconnect();
})
});
</script>
欢迎联系本站长QQ:3216572