#include <stdio.h> #include <mosquitto.h> void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str) { printf("LOG: %s\n", str); } int main(int argc, char *argv[]) { struct mosquitto *mosq = NULL; int rc; printf("Calling connect before lib init, this should fail.\n"); mosq = mosquitto_new(NULL, true, NULL); mosquitto_log_callback_set(mosq, my_log_callback); mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL); rc = mosquitto_connect(mosq, "test.mosquitto.org", 8883, 60); printf("connect returned %d\n", rc); mosquitto_destroy(mosq); mosquitto_lib_init(); printf("Calling connect after lib init, this should be fine.\n"); mosq = mosquitto_new(NULL, true, NULL); mosquitto_log_callback_set(mosq, my_log_callback); mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL); rc = mosquitto_connect(mosq, "test.mosquitto.org", 8883, 60); printf("connect returned %d\n", rc); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); printf("Calling connect after lib cleanup, this should fail.\n"); mosq = mosquitto_new(NULL, true, NULL); mosquitto_log_callback_set(mosq, my_log_callback); mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL); rc = mosquitto_connect(mosq, "test.mosquitto.org", 8883, 60); printf("connect returned %d\n", rc); mosquitto_destroy(mosq); return 0; }
运行以后报错以下:函数
➜ my-mqtt ./sub
Error: Unable to create TLS context.
OpenSSL Error: error:140A90A1:lib(20):func(169):reason(161)
Unable to connect.ui
解决方案:this
没有在开头调用初始化函数,致使没有初始化OpenSSL,在代码中加入初始化函数便可:code
mosquitto_lib_init();qt