1、MQTT Server使用EMQTTD开源库,自行安装配置;
2、JS使用Websocket连接通信。
3、JS的MQTT库为paho-mqtt,git地址:https://github.com/eclipse/paho.mqtt.javascript.git
 
代码如下:

<!DOCTYPE html>
<html> <head>
<meta charset="utf-8" />
<title></title>
<!-- <script src=“https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js” type=“text/javascript”> </script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script> <script>
var hostname = '127.0.0.1', //'192.168.1.2',
port = 8083,
clientId = 'client-mao2080',
timeout = 5,
keepAlive = 100,
cleanSession = false,
ssl = false,
// userName = 'mao2080',
// password = '123',
topic = '/World';
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>
</head> <body>
<input type="text" id="msg" />
<input type="button" value="Send" onclick="send()" />
<input type="button" value="Start" onclick="start()" />
<input type="button" value="Stop" onclick="stop()" />
</body> </html>
 

JavaScript使用MQTT的更多相关文章

  1. 使用javascript连接mqtt协议(自动重连问题)

    因为之前是在rabbitmq的插件"RabbitMQ Web MQTT plugin "中看到使用了mqttws31.js的实例,由于对mqttws31不了解,网上下载了连接成功, ...

  2. 采用MQTT协议实现android消息推送(2)MQTT服务端与客户端软件对比、android客户端示列表

    1.服务端软件对比 https://github.com/mqtt/mqtt.github.io/wiki/servers 名称(点名进官网) 特性 简介 收费 支持的客户端语言 IBM MQ 完整的 ...

  3. MQTT研究之EMQ:【EMQX使用中的一些问题记录(2)】

    我的测试环境: Linux: CentOS7 EMQX:V3.2.3 题外话: 这里主要介绍Websocket的支持问题. 对ws的支持比较正常,但是对wss的支持,调了较长的时间,没有成功. Jav ...

  4. uniapp中mqtt的基本使用

    参考文档: [1] https://www.hivemq.com/blog/mqtt-client-library-mqtt-js/ [2] https://www.tabnine.com/code/ ...

  5. paho_c_pub 使用方法

    Latest Paho Status (2) 摘自:http://modelbasedtesting.co.uk/ I last wrote about the state of Paho in Oc ...

  6. javascript mqtt 发布订阅消息

    js client使用paho-mqtt,官网地址:http://www.eclipse.org/paho/,参考http://www.eclipse.org/paho/clients/js/官网给出 ...

  7. TCP/IP, WebSocket 和 MQTT

    按照OSI网络分层模型,IP是网络层协议,TCP是传输层协议,而HTTP和MQTT是应用层的协议.在这三者之间, TCP是HTTP和MQTT底层的协议.大家对HTTP很熟悉,这里简要介绍下MQTT.M ...

  8. MQTT 消息 发布 订阅

    当连接向一个mqtt服务器时,clientId必须是唯一的.设置一样,导致client.setCallback总是走到 connectionLost回调.报connection reset.调查一天才 ...

  9. MQTT和WebSocket

    严格来说,MQTT跟WebSocket关系不大.他们不是在一个层级的.   MQTT和TCP.WebSocket的关系可以用下图一目了然:   参考资料: http://www.zhihu.com/q ...

随机推荐

  1. nmap详解之基础示例

    扫描主机target.example.com的所有TCP端口 nmap -v target.example.com 发起对target.example.com所在网络上的所有255个IP地址的秘密SY ...

  2. python基础面试集锦(51-100)

    目录 51.把aaabbbcccdd这种形式的字符串压缩成a3b3c3d2的形式? 52.给你一个字符串'abc',打印出该字符串的所有排列组合? 53.执行以下代码后,x的值为? 54.对于一个非空 ...

  3. springcloud Eureka设置服务下线上线事件通知

    最近由于微服务会莫名其妙挂掉,导致一些服务宕机: 固所以寻找解决办法,莫名宕机暂时还未查明原因,先人肉解决办法 Eureka的server端会发出5个事件通知,分别是: EurekaInstanceC ...

  4. Dwz/Jquery--使用Ajax提交表单时调用表单设置的校验

    案例 今天有一个需求就是点击按钮时,使用ajax方式提交表单,而且不是直接用form表单下的submit按钮提交,表单中用的校验是dwz 自带的校验方式,表单模板如下: <li><d ...

  5. 3万字总结,Mysql优化之精髓

    本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降. ...

  6. RestTemplate远程调用方法

    概述: spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值 ...

  7. selenium 多表单切换

    frame/iframe表单嵌套页面的应用.WebDrivr只能在一个页面上对元素识别与定位,对于在frame/iframe表单内嵌页面上的元素无法直接定位.这时需要使用 switch_to.fram ...

  8. Codeforces_733_C

    http://codeforces.com/problemset/problem/733/C 从后往前一个个b对应一组组a. #include<iostream> #include< ...

  9. Codeforces 1050D Three Religions (dp+序列自动机)

    题意: 给一个1e5的串str,然后有三个起始空串,不超过1000次操作,对三个字符串的一个尾部加一个字符或者减一个字符,保证每个字符不会超过250 每次操作之后询问你这三个串是不是可以组成str的子 ...

  10. 数据结构与算法的实现(c++)之第一天

    开发工具:codeblocks 17.12版本 学习视频来自b站 第一天:学习swap交换.冒泡排序 swap交换:swap是几乎所有的排序的最基础部分,代码如下: #include <iost ...