MQTT Client实现消息推送功能的方法详解
作者:蒙奇·D·伊丽莎白
一、MQTT
二、MQTT C Client实战
了解更多可以阅读《MQTT C Client for Posix and Windows》一文,下面根据官网资料,摘录了几个C语言实现MQTT的小DEMO。
MQTT使用起来也十分容易,基本上就那四五个函数:MQTTClient_create(创建客户端)、MQTTClient_connect(连接服务端)、MQTTClient_publishMessage(客户端->服务端发送消息)、MQTTClient_subscribe(客户端订阅某个主题)等等。其中,很多异步回调函数,需要自己去实现,如,
MQTTAsync_setCallbacks(mqtt->_client, mqtt->_client, connlost, msgarrvd, NULL);
MQTTAsync_setCallbacks中,
- connlost函数指针,是当MQTT意外断开链接时会回调的函数,由自己实现;
- msgarrvd函数指针,是当服务器有消息推送回来时,客户端在此处接受服务端消息内容。
另外,就是一些函数执行是否成功的回调函数,C语言封装回调之后,就是这么写法,看起来有些变扭。有兴趣的可以看《浅谈C/C++回调函数(Callback)& 函数指针》文章,再了解以下回调函数。
mqtt->_conn_opts.onSuccess = onConnect; mqtt->_conn_opts.onFailure = onConnectFailure;
最后,不得不说的就是,MQTT有些发送或者是订阅的内容时(某些函数中),在编程最好将参数中传进来的值在内存中拷贝一份再操作,笔者当时开发时,就是因为这样的问题,折腾了较长时间,后来在wireshark中发现数据包中根本没有内容,才知道是由于函数参数是指针形式,直接在异步中使用可能会发生一些未知的错误。
参考文档:
https://yq.aliyun.com/articles/521549?spm=5176.10695662.1996646101.searchclickresult.39f82372vfl8ed
三、MQTT client for Node.js
Installation
#You can install it as dependency with npm. $ # save into package.json dependencies with -S $ npm install aliyun-iot-mqtt -S
Usage
Aliyun IoT Hub mqtt client with authrozied by productKey & deviceName & deviceSecret.
GET Data
const Mqtt = require('aliyun-iot-mqtt'); const client = Mqtt.getAliyunIotMqttClient({ productKey: "", deviceName: "", deviceSecret: "", regionId: "cn-shanghai", keepalive:120 // mqtt options }); client.on('connect', function() { console.log("connect") }) client.end(function (){ console.log("end") })
TLS mqtts
var trustedCA = fs.readFileSync(path.join(__dirname, '/aliyun_iot_root.cer')) var options = { productKey: "", deviceName: "", deviceSecret: "", regionId: "cn-shanghai", protocol: 'mqtts', ca: trustedCA, keepalive:120 // mqtt options };
Subscribe Topic
client.subscribe(topic)
Publish Message
client.publish(topic, 'Hello mqtt') client.publish(topic, 'Hello mqtt', { qos: 1 })
Receive Message
client.on('message', function(topic, message) { console.log(topic+"," + message.toString()) })
补充:nodejs发送订阅mqtt完整示例:
var mqtt = require('mqtt'); var opt={ port:1883 } var client=mqtt.connect('tcp://10.66.28.51',opt); client.on('connect',function(){ console.log("mqtt已连接"); // client.publish('wks/cim/ASPY/#','需要发送的信息'); client.subscribe('wks/cim/ASPY/#') }) client.on('message',function(topic,msg){ console.log('收到'+topic+"讯息:"+msg.toString()); })
参考文档:
https://www.npmjs.com/package/aliyun-iot-mqtt