首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >libmosquitto无法正确重新连接

libmosquitto无法正确重新连接
EN

Stack Overflow用户
提问于 2020-12-14 21:11:24
回答 1查看 254关注 0票数 1

我正在Raspbian上试验libmosquitto dev,并且遇到了一些问题。

到目前为止,我的代码运行得非常好。我可以连接到一个代理,一旦主题得到更新,我的程序员就会打印出它应该打印的消息。这只是代理在连接后死亡并重新启动的时间点。我的代码意识到连接断开并尝试重新连接。一旦代理重新联机,我的代码就会重新连接。但从现在开始,它不会在频道上打印任何更新。

为什么不行?我认为这会很好地赶上连接,但事实并非如此。

这是我的代码:

代码语言:javascript
复制
[...]
static int run = 1;

void connect_callback(struct mosquitto *mosq, void *obj, int result)
{
        printf("connect callback, rc=%d\n", result);
}

void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
        bool match = 0;
        printf("got message '%.*s' for topic '%s'\n", message->payloadlen, (char*) message->payload, message->topic);

        mosquitto_topic_matches_sub("Heizung", message->topic, &match);
        if (match) {
            printf("got message for HEIZUNG topic\n");
    }
}


int main(int argc, char *argv[])
{
uint8_t reconnect = true;
char clientid[24];
struct mosquitto *mosq;
int rc = 0;


mosquitto_lib_init();
memset(clientid, 0, 24);
snprintf(clientid, 23, "mylog_%d", getpid());
mosq = mosquitto_new(clientid, true, 0);

if(mosq){
    mosquitto_connect_callback_set(mosq, connect_callback);
    mosquitto_message_callback_set(mosq, message_callback);

    rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60);
    mosquitto_subscribe(mosq, NULL, "Heizung", 0);

//  rc = mosquitto_loop_forever(mosq,20,5); // Tried with this function but same issue.
    while(run){
        rc = mosquitto_loop(mosq, -1, 1);
        if(run && rc){
            printf("connection error!\n");
            sleep(10);
            mosquitto_reconnect(mosq);
        }
    }
    mosquitto_destroy(mosq);
}
mosquitto_lib_cleanup();
return rc;
}

我看到的输出如下:

代码语言:javascript
复制
connect callback, rc=0
got message 'ON1' for topic 'Heizung'
got message for Heizung topic
got message 'ON2' for topic 'Heizung'
got message for Heizung topic
got message 'ON3' for topic 'Heizung'
got message for Heizung topic
connection error!
connect callback, rc=0

您会看到连接错误(其中发生了"systemctl stop systemctl“)。当代理再次返回时,您会看到重新连接似乎是成功的。但它不会打印在代理返回后由订户发送的任何新消息。并行运行mosquitto_sub命令可以看到所有消息!

你知道这里出了什么问题吗?非常感谢!

/KNEBB

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-14 21:19:27

将对mosquitto_subscribe的调用移动到connect_callback,以便在重新连接时调用它。

由于您在每次重新连接时都将CleanSession标志设置为true进行连接,因此将不会有持久会话,因此代理将不知道是否保留订阅。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65289607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档