目录
目的:前端接收mqtt消息,例如实时展示位置信息等。
1、安装MQTT服务器
可以使用网络提供的公共服务器也可以自建,例如这里安装EMQX。
输入emqx_ctl staus,出现以上说明已启动。
2、 启动emqx,woesocket
输入本地emqx地址,例如http://127.0.0.1:18083/,打开websocket页面,确定好host,port等信息并启动,后续会用到这些信息。这实际上是个mqtt管理页面,后续连接到mqtt也能在该页面查看连接状态等信息。
3、编写服务端(发布)
这里用python写(实在是方便),语言不限。mqtt以及相关库自行安装。
#coding=utf-8
import paho.mqtt.client as mqtt
import random
import json
def on_connect(client,userdata,flags,rc):
print("Connected with result code: "+str(rc))
def on_message(client,userdata,msg):
print(msg.topic+" "+str(msg.payload))
client=mqtt.Client()
client.on_connect=on_connect
client.on_message=on_message
client.connect('你的ip',1883,600)
//这边模拟输出100个点位坐标(lon,lat,height)
for i in range(0,100):
client.publish('你的topic',json.dumps({
'lon':120+random.randint(0,2000)/2000,
"lat":28+random.randint(0,2000)/2000,
"height":random.randint(0,1000)/100
},ensure_ascii=False))
4、编写客户端(订阅接收)
javascript编写客户端接受信息。
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js"></script>
<script>
var hostname = '你的ip',
port = 8083, //这里就是第二步配置的port
clientId = 'client-test',
timeout = 5,
keepAlive = 100,
cleanSession = false,
ssl = false,
topic = '你的tpic';
client = new Paho.MQTT.Client(hostname, port, clientId);
//建立客户端实例
var options = {
invocationContext: {
host: hostname,
port: port,
path: client.path,
clientId: clientId
},
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: ssl,
// userName: userName,
// password: password,
onSuccess: onConnect,
onFailure: function (e) {
console.log(e);
s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
console.log(s);
}
};
client.connect(options);
//连接服务器并注册连接成功处理事件
function onConnect() {
console.log("onConnected");
s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnected()}";
console.log(s);
client.subscribe(topic);
}
client.onConnectionLost = onConnectionLost;
//注册连接断开处理事件
client.onMessageArrived = onMessageArrived;
//注册消息接收处理事件
function onConnectionLost(responseObject) {
console.log(responseObject);
s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnectionLost()}";
console.log(s);
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
console.log("连接已断开");
}
}
function onMessageArrived(message) {
s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onMessageArrived()}";
console.log(s);
console.log("收到消息:" + message.payloadString);
}
function send() {
var s = document.getElementById("msg").value;
if (s) {
s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (s) + ", from: web console}";
message = new Paho.MQTT.Message(s);
message.destinationName = topic;
client.send(message);
document.getElementById("msg").value = "";
}
}
var count = 0;
function start() {
window.tester = window.setInterval(function () {
if (client.isConnected) {
var s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (count++) +
", from: web console}";
message = new Paho.MQTT.Message(s);
message.destinationName = topic;
client.send(message);
}
}, 1000);
}
function stop() {
window.clearInterval(window.tester);
}
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
</script>