gpt4 book ai didi

使用 mosquitto 客户端库的 C 程序无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:18 24 4
gpt4 key购买 nike

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

#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("%s\n",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=%s\n", 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;
}

关于使用 mosquitto 客户端库的 C 程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32479261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com