paho架构_Paho -物联网 MQTT C Cient的实现和详解

https://www.cnblogs.com/homejim/p/8196763.htmljavascript

概述

在文章Paho - MQTT C Cient的实现中,我介绍了如何使用Paho开源项目建立MQTTClient_pulish客户端。但只是简单的介绍了使用方法,并且客户端的结果与以前介绍的并不吻合,今天我就结合新的例子,给你们讲解一下Paho使用MQTT客户端的主要过程。

如同前面介绍的,MQTT客户端分为同步客户端和异步客户端。今天主要讲解的是同步客户端,结构仍是如同步客户端中介绍的:html

1.建立一个客户端对象;

2.设置链接MQTT服务器的选项;

3.若是多线程(异步模式)操做被使用则设置回调函数(详见 Asynchronous >vs synchronous client applications);

4.订阅客户端须要接收的任意话题;

5.重复如下操做直到结束:

a.发布客户端须要的任意信息;

b.处理全部接收到的信息;

6.断开客户端链接;

7.释放客户端使用的全部内存。java

实现

好,直接上代码,MQTT简单的同步客户端。nginx

#include

#include #include #include #include "MQTTClient.h" #if !defined(WIN32) #include #else #include #endif #define NUM_THREADS 2 #define ADDRESS "tcp://localhost:1883" //更改此处地址 #define CLIENTID "aaabbbccc_pub" //更改此处客户端ID #define SUB_CLIENTID "aaabbbccc_sub" //更改此处客户端ID #define TOPIC "topic01" //更改发送的话题 #define PAYLOAD "Hello Man, Can you see me ?!" // #define QOS 1 #define TIMEOUT 10000L #define USERNAME "test_user" #define PASSWORD "jim777" #define DISCONNECT "out" int CONNECT = 1; volatile MQTTClient_deliveryToken deliveredtoken; void delivered(void *context, MQTTClient_deliveryToken dt) { printf("Message with token value %d delivery confirmed\n", dt); deliveredtoken = dt; } int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) { int i; char* payloadptr; printf("Message arrived\n"); printf(" topic: %s\n", topicName); printf(" message: "); payloadptr = message->payload; if(strcmp(payloadptr, DISCONNECT) == 0){ printf(" \n out!!"); CONNECT = 0; } for(i=0; ipayloadlen; i++) { putchar(*payloadptr++); } printf("\n"); MQTTClient_freeMessage(&message); MQTTClient_free(topicName); return 1; } void connlost(void *context, char *cause) { printf("\nConnection lost\n"); printf(" cause: %s\n", cause); } void *subClient(void *threadid){ long tid; tid = (long)threadid; printf("Hello World! It's me, thread #%ld!\n", tid); MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; int rc; int ch; MQTTClient_create(&client, ADDRESS, SUB_CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.username = USERNAME; conn_opts.password = PASSWORD; MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered); if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { printf("Failed to connect, return code %d\n", rc); exit(EXIT_FAILURE); } printf("Subscribing t

你可能感兴趣的:(paho架构)