C程序使用蚊到客户端库不工作



谁能告诉我为什么下面的代码不工作?

#include<mosquitto.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
    char id[4] = "4567";
    char *host = "localhost";
    int port = 61613;
    int keepalive = 60;
    const char *msg1 = "{ "data":"Hello" }";
    bool clean_session = false;
    const char *top = "data/test/abc";
    struct mosquitto *mosq = NULL;
    mosquitto_lib_init();
    mosq = mosquitto_new(id,clean_session,NULL);
    if(!mosq){
        printf("Not Created");
        return 1;
    }
    mosquitto_username_pw_set(mosq,"admin","password");
    printf("%sn",mosquitto_strerror(mosquitto_connect(mosq,host,port,keepalive)));
    int err = mosquitto_publish(mosq,NULL,"admin",strlen(msg1),msg1,1,true);
    printf("Error number: %d",err);
    printf("nerr description=%sn", mosquitto_strerror(err));  

    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
    return 0;
}

我正在使用apollo broker,我编译了代码,它的工作没有任何错误,但是发布的消息没有到达broker

您应该查看mosquitto_loop*()函数,您需要使用其中一个函数来确保处理网络流量。mosquitto_publish()是完全异步的,当它返回时不保证交付。如果您想确保消息已经传递,请使用on_publish回调。

我建议这样做:

void on_publish(struct mosquitto *mosq, void *userdata, int mid)
{
    mosquitto_disconnect(mosq);
}
int main(int argc, char *argv[])
{
    struct mosquitto *mosq;
    mosq = mosquitto_new("id", true, NULL);
    mosquitto_publish_callback_set(mosq, on_publish);
    mosquitto_connect(mosq, "example.net", 1883);
    mosquitto_publish(mosq, NULL, "topic, 11, "hello world", 0, false);
    mosquitto_loop_forever(mosq, -1, 1);  // this calls mosquitto_loop() in a loop, it will exit once the client disconnects cleanly
    return 0;
}

相关内容

  • 没有找到相关文章

最新更新