MQTT C Client实现消息推送(入门指南)

一、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

aliyun_iot_root.cer

 
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())

})

 

参考文档:

https://www.npmjs.com/package/aliyun-iot-mqtt

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MQTT(Message Queuing Telemetry Transport)是一种轻量级的消息传输协议,常用于物联网设备之间的通信。在Java中,可以使用Eclipse Paho库来实现MQTT协议的消息推送。 首先,你需要在项目中引入Eclipse Paho库的依赖。可以在Maven项目中的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.5</version> </dependency> ``` 接下来,你可以使用以下代码实现MQTT协议的消息推送: ```java import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class MqttPublisher { public static void main(String[] args) { String broker = "tcp://mqtt.eclipse.org:1883"; // MQTT broker地址 String clientId = "JavaPublisher"; // 客户端ID String topic = "test/topic"; // 发布的主题 int qos = 1; // 消息质量 try { MqttClient client = new MqttClient(broker, clientId, new MemoryPersistence()); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); System.out.println("Connecting to broker: " + broker); client.connect(connOpts); System.out.println("Connected"); String content = "Hello, MQTT!"; MqttMessage message = new MqttMessage(content.getBytes()); message.setQos(qos); System.out.println("Publishing message: " + content); client.publish(topic, message); System.out.println("Message published"); client.disconnect(); System.out.println("Disconnected"); } catch (MqttException e) { e.printStackTrace(); } } } ``` 上述代码中,我们创建了一个MqttClient对象,并指定了MQTT broker的地址、客户端ID、发布的主题和消息质量。然后,我们连接到MQTT broker,发布一条消息,最后断开连接。 请注意,上述代码仅为示例,你需要根据实际情况修改broker地址、客户端ID、主题和消息内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值