2 wjw173 wjw173 于 2016.02.22 14:44 提问

mqttkit 如何取消自动重连

如题,项目需要,我们用mqtt协议做远程控制。通信双方为mqtt服务器和两个ios APP,A和B .
现在我用同一个账号(如账号:32456@qq.com 密码:123456)先在A客户端登录,然后再用这个账号登录B客户端。这时B会把A挤掉,重新连上,(重连成功后发订阅,也会一直发订阅)。待B登陆成功,A掉线后,A又自动重连。就这样一直挤掉对方。请问该如何取消mqtt Client的自动重连?

2个回答

wjw173
wjw173   2016.02.25 16:09

int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets)
{
int run = 1;
int rc;
unsigned int reconnects = 0;
unsigned long reconnect_delay;

if(!mosq) return MOSQ_ERR_INVAL;

if(mosq->state == mosq_cs_connect_async){
    mosquitto_reconnect(mosq);
}

while(run){
    do{
        rc = mosquitto_loop(mosq, timeout, max_packets);
        if (reconnects !=0 && rc == MOSQ_ERR_SUCCESS){
            reconnects = 0;
        }
    }while(rc == MOSQ_ERR_SUCCESS);
    if(errno == EPROTO){
        return rc;
    }
    pthread_mutex_lock(&mosq->state_mutex);
    if(mosq->state == mosq_cs_disconnecting){
        run = 0;
        pthread_mutex_unlock(&mosq->state_mutex);
    }else{
        pthread_mutex_unlock(&mosq->state_mutex);

        if(mosq->reconnect_delay > 0 && mosq->reconnect_exponential_backoff){
            reconnect_delay = mosq->reconnect_delay*reconnects*reconnects;
        }else{
            reconnect_delay = mosq->reconnect_delay;
        }

        if(reconnect_delay > mosq->reconnect_delay_max){
            reconnect_delay = mosq->reconnect_delay_max;
        }else{
            reconnects++;
        }

#ifdef WIN32
Sleep(reconnect_delay*1000);
#else
sleep(reconnect_delay);
#endif

        pthread_mutex_lock(&mosq->state_mutex);
        if(mosq->state == mosq_cs_disconnecting
           || mosq->state == mosq_cs_connected){
            run = 0;
            pthread_mutex_unlock(&mosq->state_mutex);
        }else{
            pthread_mutex_unlock(&mosq->state_mutex);
            mosquitto_reconnect(mosq);
        }
    }
}
return rc;

}

wjw173
wjw173   2016.02.25 16:17

if(mosq->state == mosq_cs_disconnecting
|| mosq->state == mosq_cs_connected){
run = 0;

                    mqtt client 链接到服务器后,mosq->state 的状态是mosq_cs_connected,原来是if(mosq->state == mosq_cs_disconnecting
       ){
        run = 0;
                    }
                    要想跳出循环。在状态是mosq_cs_connected的时候也要跳出循环,在mosq_loop_forever(){}里设置 run = 0;就可以避免自动重连的while循环。
                    mqttkit 很久之前就没有更新了,mqttclient 会比较好点。ios的关于mqtt第三方库还是少了点。还有只支持swift 的cocomqtt.
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!