参考代码
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