最近做了一个项目,用到了mqtt,觉得特别好用,可以把消息直接推送到web端,手机端等不同的终端,太方便了,于是专门写了个简单的demo,代码比较简单,但是包括了mqtt消息的发送和监听,我用的是jQuery来实现的,所以引用了mqttws31.js这个文件,该文件一并放到源码里面,大家可以下载。
<html>
<head>
<title>基于jQuery的mqtt消息监听</title>
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/mqttws31.js"></script>
<script>
$().ready(function(){
MQTTconnect();
$("#sendMsg").click(function(){
sendMessageToMqtt($("#msg").val());
$("#msg").val("");
});
});
var hostname="**************";//mqtt服务器主机地址
var hostPort="***";//mqtt服务器端口号
var sub_count = 0;
var client;
var timeout = 5;
var keepAlive = 100;
var clientId = guid();
function MQTTconnect() {
client = new Paho.MQTT.Client(hostname, hostPort, clientId);
client.onMessageArrived = onMessageArrived;
var options = {
invocationContext: {
host: hostname,
port: hostPort,
path: "/mqtt",
clientId: clientId
},
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: false,
useSSL: false,
// userName: userName,
// password: password,
onSuccess: onConnect,
onFailure: function (e) {
alert("连接失败");
}
};
client.connect(options);
};
function onConnect() {
client.subscribe("test/msg"); //订阅主题
}
//发送消息
function sendMessageToMqtt(msg)
{
var message = new Paho.MQTT.Message(msg);
message.destinationName = "test/msg";
message.qos=0;
client.send(message);
}
//收到消息后的处理函数
function onMessageArrived(message) {
var topic = message.destinationName;
var payload = message.payloadString;
$("#reciveMsg").append($("<div>"+payload+"</div>"));
}
//生成随机的clientid
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
function guid() {
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
</script>
</head>
<body>
<div><input type="text" id="msg" style="width: 100%;"></div>
<div style="margin-top: 5px;"><input type="button" id="sendMsg" value="发送消息"></div>
<div style="margin-top: 20px;">
<div>收到的消息:</div>
<div id="reciveMsg"></div>
</div>
</body>
</html>