Paho js mqtt客户端触发onConnect事件

时间:2018-08-31 22:11:34

标签: javascript client mqtt paho

我正在使用Paho js客户端连接到mosquitto。它连接确定。但是onConnect事件正在不停地触发。我正在检查代理中的日志,它似乎只连接了一次。为什么会这样呢?我只是使用了在官方网站上浏览的代码:

 <html>
   <head>
      <title>JavaScript MQTT WebSocket Example</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/paho- mqtt/1.0.1/mqttws31.js" type="text/javascript">
     </script>
     <script type = "text/javascript" language = "javascript">
           var host = "192.168.1.200";
        var port = 1884;
        // Create a client instance
         client = new Paho.MQTT.Client(host, port, "abcd");

     // set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

// connect the client
client.connect({onSuccess:onConnect});


// called when the client connects
function onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  client.subscribe("World");
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "World";
  client.send(message);
    console.log("messageSent");
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

// called when a message arrives
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}

      </script>
   </head>
     <body>
   <h1>Main Body</h1>
    <script>
    </script>
   </body>  
</html>

1 个答案:

答案 0 :(得分:0)

当我的客户ID(此处为“ abcd”)已经连接时,我通常会注意到这一点。为了在多个设备上进行部署,我将此设置为UUID。