【问题标题】:onFailure function in mqtt javascript clientmqtt javascript客户端中的onFailure函数
【发布时间】:2017-03-23 11:32:30
【问题描述】:

我正在使用 mqtt paho javascript 客户端库连接到 mqtt 服务器,我可以使用用户名和密码连接到服务器,现在的问题是......如果用户输入错误的用户名或密码,我如何警告用户。i followed this link 如果用户凭据错误,是否有任何 onFailure 函数来报告错误??

client.connect({onSuccess:this.onConnect.bind(this),userName:Name,password:Password},{onFailure:console.log("failed")});



  onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  
  }

即使我能够连接,我也只能在控制台中看到“onConnect”和“失败”消息

【问题讨论】:

    标签: mqtt paho


    【解决方案1】:

    您需要阅读经纪人将为您带来的连接返回码字段

    协议中定义了一个常量列表:

    你要找的是:

    0x04 连接被拒绝,用户名或密码错误

    指定的其他值是:

    0x00:已接受连接

    0x01:连接被拒绝

    0x02:连接被拒绝

    0x03:连接被拒绝

    0x04:连接被拒绝

    0x05:连接被拒绝,未授权

    从 6-255:保留以供将来使用

    【讨论】:

    • 能否请您提供一个示例,如何阅读 Broker 带来的 Connect Return code 字段。
    【解决方案2】:

    取自文档here

    Paho connect 方法采用 options 参数,其中包含一个 onFailure 回调函数,该函数将包含身份验证失败的错误代码:

    client.connect({
      onFailure: function(err) {
        if (err.errorCode == 0x4) {
          //bad user/password
        }
      }
    });
    

    【讨论】:

    • client.connect({ onFailure: function(err) { if (err.errorCode == 0x4) { //bad user/password } }, {onSuccess:this.onConnect.bind(this) ,用户名:"用户",密码:"123"}});
    • 我使用了上面的代码,但没有收到任何错误消息
    • 该代码不会向您显示错误,它只是告诉您在哪里处理错误,您必须自己添加该位
    • 我在 onFailure 函数中写了“console.log(err);”,但在控制台中看不到任何内容
    【解决方案3】:

    connect 方法将 connectionOptions 作为参数,因此您可以提供 onSuccess、onFailure、userName、password 等选项。将单个响应对象参数传递给具有 errorCode 等字段的 onFailure 回调 ,错误信息。

    client.connect({onSuccess:this.onConnect.bind(this),
    userName:uName,
    password:uPassword,
    onFailure:this.onFailure.bind(this)
    });
    onConnect() {
      // Once a connection has been made, make a subscription and send a message.
      console.log("onConnect");
         }
    onFailure(responseObject){
      console.log("you have no access to the connnection!!!");
      console.log(responseObject);
     }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多