Paho MQTT C++ 连接用户和密码

问题描述 投票:0回答:2

我正在实现一个客户端来通过 MQTT 发送数据,并且我正在使用 Paho MQTT c++ 库。 现在我需要添加对用户和密码身份验证的支持,当我尝试像这样设置它们时:

std::string user = "user";
std::string password = "password";
mqtt::connect_options connOpts;
connOpts.set_user_name(user);
connOpts.set_password(password);

我明白了

对 mqtt::connect_options::set_user_name(std:string) 的未定义引用 常量&)

但是在头文件connection_options.h中

/**
 * Sets the user name to use for the connection.
 * @param userName 
 */
void set_user_name(const std::string& userName);

同样的事情发生在 set_password(password);

我遇到的另一个问题是我无法保持连接处于活动状态,因为我无法在类中全局使用 mqtt::async_client 对象,我只能在发布函数中创建它。

提前致谢。

c++ authentication connection mqtt paho
2个回答
1
投票

我遇到了这个问题,并通过在 connect_options.h 中的 set_user_nameset_password 函数中添加我自己的代码来修复它(这些代码未在 C++ 包装器中的任何其他文件中初始化)。

void set_user_name(const std::string& userName){
    const char * usr = userName.c_str();
    opts_.username = usr;
}


void set_password(const std::string& password){
    const char * pw = password.c_str();
    opts_.password = pw;
}

0
投票

请尝试这个:

auto connOpts = mqtt::connect_options_builder()     
    .clean_session()
    .user_name("User name here")                  // put username here
    .password(binary_ref_passwd)
    .will(mqtt::message(TOPIC, LWT_PAYLOAD, QOS))
    .finalize();
© www.soinside.com 2019 - 2024. All rights reserved.