没有通过WebSocket从Mosquitto接收有效载荷

时间:2019-05-15 11:12:17

标签: websocket vps mosquitto

我正在使用VPS,并且正在通过MQTT将数据从Arduino发送到服务器。

Mosquitto通过终端成功打印有效载荷,但是当我尝试通过网页实时打印有效载荷时,

如果运行,知道我已经在Mosquitto conf中允许使用websocket了:

{
    "france": [{
        "manager": "Corinne Diacre",
        "world-ranking": "5"
    }],
    "england": [{
        "manager": "Phil Neville",
        "world-ranking": "2"
    }]
}

我明白了:

connect2you.com.List list = new connect2you.com.List (id, name, genre);

我要发送的主题名称是/ pression,而我使用的代码是:

sudo netstat -plnt

当我运行脚本时,它说“ Mqtt Connected”,什么也没发生。

但是如果我在终端中运行:

tcp        0      0 0.0.0.0:1883            0.0.0.0:*               LISTEN      
13248/mosquitto
tcp        0      0 0.0.0.0:1884            0.0.0.0:*               LISTEN      
20169/mosquitto
tcp6       0      0 :::1883                 :::*                    LISTEN      13248/mosquitto

我得到了压力值。

如果我将网页保持打开状态几分钟,则会收到此消息:

  <script>

    var websocket="myserver.ovh.net";
    var port= 1884;
    var user="username";
    var pass="password";


    client = new Paho.MQTT.Client(websocket, port, "innovation");


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

  var options = {
   useSSL: false,
   userName: user,
   password: pass,
   onSuccess:onConnect,
   onFailure:doFail
}

// connect the client

client.connect(options);


// called when the client connects

 function onConnect() {
// Once a connection has been made, make a subscription and send a 
message.


 document.getElementById("connstatus").innerHTML = "Mqtt Connected";

 console.log("Mqtt Connected");

  client.subscribe("/pression");

    }

    function doFail(e){
    console.log(e);
   }

   // called when the client loses its connection
    function onConnectionLost(responseObject) {

  document.getElementById("connstatus").innerHTML = "Mqtt Not Connected";

     if (responseObject.errorCode !== 0) {
         console.log("onConnectionLost:"+responseObject.errorMessage);
    }
   }

   function onMessageArrived(message) {
   console.log("Pression is :");
   document.getElementById("connstatus").innerHTML = message.payloadString;
   console.log(message.payloadString);

   }


  </script>

配置文件:

         mosquitto_sub -t '/pression'

蚊子日志:

       Mqtt Connected
       test.html:76 onConnectionLost:AMQJS0008I Socket closed.

1 个答案:

答案 0 :(得分:-1)

好的,这里的问题很可能是您在HTML中使用了固定的客户端ID(innovation)。

您只能将1个客户端与给定的客户端ID连接,因此当连接具有相同ID的新客户端(例如,重新加载页面)时,代理将断开最旧的客户端的连接。

尝试将连接线更改为以下内容:

var clientID = "innovation_" + new Date().getTime();
client = new Paho.MQTT.Client(websocket, port, clientID);
相关问题