html+js网页连接MQTT服务器new Paho.MQTT.Client
发布时间:2024年01月18日
网页完整代码示例
<!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>
<div class="title" id="title">
<br><br>
<h3 align="center">简单测试</h3>
<center><input type="button" value="开始" onclick="test()"></center>
</div>
<script src="https://cdn.bootcss.com/paho-mqtt/1.0.2/mqttws31.min.js"></script>
<script>
client = new Paho.MQTT.Client("broker.emqx.io", Number(8083), "websockets-test");
client.connect({ onSuccess: onConnect });
function onConnect() {
console.log("onConnected");
topic = 'mytopic';
client.subscribe(topic);
console.log("subscribed");
}
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("连接已断开");
}
}
function onMessageArrived(message) {
console.log("收到消息:" + message.payloadString);
console.log("主题:" + message.destinationName);
}
function test() {
console.log('按钮点击')
}
</script>
</body>
</html>
运行效果:
文章来源:https://blog.csdn.net/weixin_43361722/article/details/135663347
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!