我正在尝试订阅使用 SSL/TLS 对客户端进行身份验证的 mqtt 代理。我使用libmosquitto来做到这一点。
我运行此代码来执行订阅
#include <csignal>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <mosquitto.h>
#define WITH_AUTHENTICATION
#define MQTT_HOST "exmaple.com"
#define MQTT_PORT 8883
#define TARGET_USER "use"
#define TARGET_PW "password"
#define TARGET_TOPIC "/example-topic"
#define CERTIFICATE "/home/luca/TRIALS/tryMqttS/cert.pem"
using namespace std;
static int run = 1;
void signalHandler (int s) {
run = 0;
}
void messageCallback (struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) {
bool match = 0;
cout << "got message " << (char *) message->payload << " from topic " << message->topic << endl;
}
int main(int argc, char *argv[])
{
uint8_t reconnect = true;
string clientID = "mosquitto_client_" + to_string (getpid());
struct mosquitto *mosq = nullptr;
int resCode = 0;
signal (SIGINT, signalHandler);
signal (SIGTERM, signalHandler);
mosquitto_lib_init ();
mosq = mosquitto_new (clientID.c_str(), true, 0);
if(mosq){
mosquitto_message_callback_set (mosq, messageCallback);
#ifdef WITH_AUTHENTICATION
cout << "Pw set result: " << mosquitto_strerror (mosquitto_username_pw_set (mosq, TARGET_USER, TARGET_PW)) << endl;
cout << "Tls insecure set result: " << mosquitto_strerror (mosquitto_tls_insecure_set (mosq, false)) << endl;
cout << "Tls opts set result: " << mosquitto_strerror (mosquitto_tls_opts_set (mosq, 1, NULL, NULL)) << endl;
cout << "Tls set result: " << mosquitto_strerror (mosquitto_tls_set (mosq, CERTIFICATE, nullptr, nullptr, nullptr, /*pw_cb * */ nullptr)) << endl;
#endif
cout << "Connection result: " << mosquitto_strerror (mosquitto_connect (mosq, MQTT_HOST, MQTT_PORT, 60)) << endl;
cout << "Subscription result: " << mosquitto_strerror (mosquitto_subscribe (mosq, NULL, TARGET_TOPIC, 0)) << endl;
while (run) {
resCode = mosquitto_loop (mosq, 20, 1);
if (resCode) {
cout << "ERROR: " << mosquitto_strerror (resCode) << " (" << resCode << ")\n";
sleep(1);
mosquitto_reconnect (mosq);
}
}
mosquitto_destroy (mosq);
}
mosquitto_lib_cleanup ();
return 0;
}
但输出每次都是一样的:
Connection result: 0
Subscription result: 0
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
使用外部工具(例如mqttfx)并使用相同的身份验证凭据,订阅很好,我可以接收在主题上发布的消息。
如何正确执行订阅?是否缺少一些设置?