centos下面Paho Client编写mqtt同步的C程序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lcr_happy/article/details/89281644

根据官网文档,下载官方仓库并且在自己的电脑上安装了paho-mqtt的包。
具体操作可参考我的博客:
https://blog.csdn.net/lcr_happy/article/details/89279507

新建一个文件叫synchronous_mqtt_test.c:

#include <string.h>
#include "MQTTClient.h"
#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientPub"
//注意我这边设置的主题是/hello
#define TOPIC       "/hello"  
#define PAYLOAD     "Hello World!"
#define QOS         1
#define TIMEOUT     10000L
int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    int rc;
    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    pubmsg.payload = PAYLOAD;
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    printf("Waiting for up to %d seconds for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
    rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
    printf("Message with delivery token %d delivered\n", token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;

上面这段代码的前提是你在本地安装了mqtt服务器,如果不是安装在本地的话。localhost需要修改为实际的mqtt服务器的地址,端口如果不一致的话也需要做相应的修改,我在本地是使用docker来运行一个eclipse-mosquito务的,具体安装可以参照官网文档。

编写完上面的代码之后,我们就来编译生成可执行文件了。
1、将/usr/local/lib引入到ld.so.conf里面,我这里是采用在ld.so.conf新建一个paho-mqtt3.conf的文件在里面加上:

/usr/local/lib

保存退出之后一定记得执行ldconfig使修改生效。

2、执行:

gcc synchronous_mqtt_test.c -lpaho-mqtt3c

其中-lpaho-mqtt3c是指定动态链接库,因为我们这里是同步的,所以需要使用的链接库是libpaho-mqtt3c.so.

执行之后就可以看到a.out的绿色可执行文件了,是不是很激动。

希望,执行:

./a.out

你看到的是:
在这里插入图片描述
祝好运!done

补充:
如果此时你使用tongxinmao.com上面的mqtt服务器助手测试的话:
测试你将看到当你实现订阅了/hello这个主题的话,等你程序一运行的话你就可以在这里看到浏览器里面收到了你程序发布的消息。


猜你喜欢

转载自blog.csdn.net/lcr_happy/article/details/89281644