javascript-mqtt

js client使用paho-mqtt,官网地址:http://www.eclipse.org/paho/,参考http://www.eclipse.org/paho/clients/js/官网给出例子Getting Started,写出下面简单的测试代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Centos7 mosquitto test</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="paho-mqtt-min.js"></script>
<script type="text/javascript">
var hostname = "csxyz.xyz";      //主机IP  106.14.181.32
var hostPort = 9001;             //port
var sub_count = 0;
var client;
function MQTTconnect() {
    client = new Paho.MQTT.Client(hostname, hostPort, "test");
    client.onMessageArrived = onMessageArrived;
    client.connect({onSuccess:onConnect});
    console.log("Host="+ hostname + ", port=" + hostPort);
};
// called when the client connects
function onConnect() {
  console.log("onConnect succeeds");
//  client.subscribe('topic');
  client.subscribe('#');    //订阅所有主题
}
// called when a message arrives
function onMessageArrived(message) {
    var topic = message.destinationName;
    var payload = message.payloadString;
    console.log("onMessageArrived:" + payload);
    sub_count++;
   $('#sub_count').val('收到订阅' + sub_count + '条');
   $('#sub_message').prepend('<li>' + topic + ' = ' + payload + '</li>');
}
function button_onclick(){
    var topic = $('#topicsend').val();
    var text = $('#textsend').val();
    if(topic=='' || text=='')
    {
        alert("noTopic or noText");
        return;
    }
    var message = new Paho.MQTT.Message(text);
    message.destinationName = topic;
    message.qos=0;
    client.send(message);
};
$(document).ready(function() {
    MQTTconnect();
});
</script>
</head>
 
<body>
<h1>mosquitto pub</h1>
topic:<input type='text' id='topicsend' size="60"/> <br>
text :<input type='text' id='textsend' size="60"/>
<input type='button' value="send" id='btn' onclick="button_onclick()"/>
</br>
<h1>mosquitto sub</h1>
<input type='text' id='sub_count' disabled />
<ul id='sub_message' ></ul>
</body>
</html>

html在本地运行,测试结果:

javascript-mqtt

在censtos的apache空间根目录下创建文件夹iot,将index.html和需要包含的js文件拷贝过去,使用浏览器打开csxyz.xyz/iot,也可以得到上面的结果。注意,文件上传的时候是在root用户下,需要更改权限,否则运行会报错的。

上一篇:pandas聚合aggregate


下一篇:关于elementui表单数字校验踩坑记