paho mqtt 重连后无法订阅问题

本文探讨了使用Paho MQTT C库时遇到的重连后无法自动订阅的问题。通过分析官方示例代码,提出了两种方法:1) 设置`cleanstart`为0,但可能导致新部署的MQTT服务器清除数据后客户端无法订阅;2) 查看并分析`paho_c_sub.c`完整代码以寻求解决方案。
摘要由CSDN通过智能技术生成

参考代码

https://github.com/eclipse/paho.mqtt.c/blob/master/src/samples/paho_c_sub.c

方法1:

conn_opts.cleanstart = 0;

缺点:

当我把mqtt server 清除数据重新部署后,mqtt client reconnect后,无法自动订阅;

 

方法2:

 

conn_opts.cleanstart = 0;

......


while (1)
    {
        mysleep(1000);

        if (finished)
        {
            MQTTAsync_disconnect(client, &disc_opts);
            printf("reconnet\n");
            finished = 0;
            MQTTAsync_connect(client, &conn_opts);
        }
    }

 完整代码 paho.mqtt.c-master\src\samples\paho_c_sub.c

/*******************************************************************************
 * Copyright (c) 2012, 2018 IBM Corp., and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *   http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Ian Craggs - initial contribution
 *    Ian Craggs - fix for bug 413429 - connectionLost not called
 *    Guilherme Maciel Ferreira - add keep alive option
 *    Ian Craggs - add full capability
 *******************************************************************************/

#include "MQTTAsync.h"
#include "MQTTClientPersistence.h"
#include "pubsub_opts.h"

#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>


#if defined(WIN32)
#include <windows.h>
#define sleep Sleep
#else
#include <sys/time.h>
#include <unistd.h>
#endif

#if defined(_WRS_KERNEL)
#include <OsWrapper.h>
#endif

volatile int finished = 0;
int subscribed = 0;
int disconnected = 0;


void mysleep(int ms)
{
	#if defined(WIN32)
		Sleep(ms);
	#else
		usleep(ms * 1000);
	#endif
}

v
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值