mqtt 服务器与客户端通讯

Posted singularity

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mqtt 服务器与客户端通讯相关的知识,希望对你有一定的参考价值。

mqtt 服务器与客户端通讯。

服务器端

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
64
/**
* Created by niyl on 2016/1/13.
*/
 
var mosca = require(‘mosca‘);
var MqttServer = new mosca.Server({
port: 8000
});
/**
* 验证方法
*
**/
var authenticate = function(client, username, password, callback) {
//var authorized = (username.toString() === ‘18FE34F48379-DC‘ && password.toString() === ‘666666‘);
var authorized = (password.toString() === ‘666666‘);
if (authorized){
//存储设备类型
client.type = username.toString().split(‘-‘)[1];
}
callback(null, authorized);
}
 
 
//
 
MqttServer.on(‘clientConnected‘, function(client){
console.log(‘client connected‘, client.id);
});
 
/**
* 监听MQTT主题消息
**/
MqttServer.on(‘published‘, function(packet, client) {
var topic = packet.topic;
// console.log(‘message-arrived--->‘,‘topic =‘+topic+‘,message = ‘+ packet.payload.toString());
switch(topic){
case ‘pubMsg‘:
console.log(‘message-publish‘, packet.payload.toString());
//MQTT转发主题消息
MqttServer.publish({topic: ‘other‘, payload: ‘hello‘});
//发送消息NODEJS
console.log(‘HD: ‘);
//发送socket.io消息
//io.sockets.socket(YHSocketMap.get(‘1000‘)).emit(‘subState‘, packet);
break;
case ‘other‘:
console.log(‘message-123‘, packet.payload.toString());
break;
case ‘order‘:
console.log(‘order‘, packet.payload.toString());
 
break;
case ‘test‘:
console.log(‘test‘, packet.payload.toString());
break;
}
 
 
});
 
MqttServer.on(‘ready‘, function(){
console.log(‘mqtt is running...‘);
//MqttServer.authenticate = authenticate;
});



客户端程序

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
var mqtt = require(‘mqtt‘);
 
 
var client = mqtt.createClient(8000, ‘localhost‘,{clientId:‘1‘,clean:false});
//向服务器订阅一个主题
client.subscribe(‘other‘,{qos:1});
client.subscribe(‘test‘,{qos:1});
//当消息到达时
var yy=0;
var ww=0;
client.on(‘message‘, function (topic, message) {
var tt=(message.toString());
console.log(tt);
switch(tt)
{
case ‘redd‘ :
ww++;
console.log(10000-ww);
break;
case ‘hello‘ :
yy++;
console.log(yy);
break;
}
 
});
// PUBLISH-发布消息
var num=0;
setInterval(function (){
client.publish(‘order‘, ‘ ‘ + (num++),{qos:1, retain: true});
console.log("num="+num);
}, 5000);
setInterval(function(){
client.publish(‘pubMsg‘, ‘send ‘ );
// console.log("PubMsg");
},10000);
setInterval(function(){
client.publish(‘test‘, ‘redd‘ );
// console.log("test");
},20000);
 
 
var start=Date.now();
console.log("服务端"+start);


以上是关于mqtt 服务器与客户端通讯的主要内容,如果未能解决你的问题,请参考以下文章

MQTT与Mosquitto服务器搭建以及Android推送MQTT简介

mqtt与socket的区别

ESP8266如何实现与服务器的TCP通讯

1.2MQTT基本原理

MQTT简单介绍与实现

Windows上Mqtt服务器搭建与使用客户端工具MqttBox进行测试