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. STVP编译时遇到no default placement for segment .FLASH_CODE

    最近编译STM8S003时需要使用flash库函数,看起来简单,实则折腾了超过1天.今天总结方法如下: 1.修改stm8s.h 156行  #define RAM_EXECUTION  注释去掉  如 ...

  2. flask中使用SQLAlchemy操作mysql的一些注意事项和坑

    一 ImportError: cannot import name 'db' 由于app最后才加载,所以其他文件,比如models.py不能从app.py导入任何变量, 要使用db可以先定义一个,之后 ...

  3. Flutter 入门 --- 内部分享

    八月部门给分配的分享任务,由于项目太赶,推迟一个月. 选 Flutter 这个主题,是因为现在它慢慢流行起来了,而我却不了解,故而借此契机,上手试试. 简介 Flutter 是 Google 推出的跨 ...

  4. 深入JVM垃圾回收机制,值得你收藏

    JVM可以说是为了Java开发人员屏蔽了很多复杂性,让Java开发的变的更加简单,让开发人员更加关注业务而不必关心底层技术细节,这些复杂性包括内存管理,垃圾回收,跨平台等,今天我们主要看看JVM的垃圾 ...

  5. 开发中常见的common.js--1

    common.js 1.基于代码重用的目的,方便在页面中调用: 2.跟普通的js包含文件并没有其他不一样,主要是一些js经常用到的函数,或者字符串.数组方法的简单扩展: 3.封装的兼容性的方法.[po ...

  6. 【TensorFlow】TensorFlow获取Variable值,将Variable保存为list数据

    Variable类型对象不能直接输出,因为当前对象只是一个定义. 获取Variable中的浮点数需要从数据流图获取: initial = tf.truncated_normal([3,3], stdd ...

  7. DOCKER绝对领域从2048到4069?不:25519,数字的飞跃,HTTP/2

    这个标题花了几分钟,远远超过我构思以下内容的时间损耗,希望大家且看且珍惜,因为这是为数不多的cnblog特别标题 我记得很久以前,我开了一系列随笔,从第一篇揭发233的docker/machine开始 ...

  8. vue学习(二)模板页配置(bootstrap)

    1.替换我们的显示页面 删除components下的所有文件,新建模板页文件夹 layout. //Layout.vue <template> <div> <header ...

  9. CentOS6.5下部署SVN

    查看系统版本,安装SVN软件及创建目录 [root@A-linux ~]# uname -r 2.6.32-431.el6.x86_64 [root@A-linux ~]# cat /etc/redh ...

  10. Force removing ActivityRecord no saved state问题的原因分析

    关键字,crash Force removing ActivityRecord,app died, no saved state的原因 相机拍摄的过程中断电,拍了一张黑图 I/ActivityMana ...