简体   繁体   English

Node.js与Java之间的mqtt通信

[英]mqtt communication between node.js and java

Goal is to send data using mqtt protocol. 目标是使用mqtt协议发送数据。 Java project (tempSensor) produce tempvalue using mqtt protocol and node.js which subscribe tempvalue using mqtt. Java项目(tempSensor)使用mqtt协议和node.js生成温度值,后者使用mqtt预订温度值。 Both node.js and java project use same key for publish/subscribe. node.js和java项目都使用相同的密钥进行发布/订阅。 I am able to publish data using java project and also subscribe data in node.js. 我可以使用Java项目发布数据,也可以在node.js中订阅数据。 But data is not in readable format. 但是数据不是可读格式。 How to do it ? 怎么做 ? So that data is in readable format. 因此该数据为可读格式。 Structure for TempStruct is as below: TempStruct的结构如下:

public class TempStruct implements Serializable {
private static final long serialVersionUID = 1L;

private double tempValue;

public double gettempValue() {
    return tempValue;
}

private String unitOfMeasurement;

public String getunitOfMeasurement() {
    return unitOfMeasurement;
}

public TempStruct(double tempValue, String unitOfMeasurement) {

    this.tempValue = tempValue;
    this.unitOfMeasurement = unitOfMeasurement;
}

public String toJSON() {
      String json = String.format("{'tempValue': %f, 'unitOfMeasurement': '%s'}", tempValue, unitOfMeasurement);
      return json;
    }
   }

Code which published data using mqtt is as below: 使用mqtt发布数据的代码如下:

Logger.log(myDeviceInfo.getName(), "TemperatureSensor",
                "Publishing tempMeasurement");
        System.out.println("JSON Value...."+newValue.toJSON());
        try {
            this.myPubSubMiddleware.publish("tempMeasurement",
                    newValue.toJSON().getBytes("utf-8"), myDeviceInfo);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Code which received data using mqtt is shown below:(Node.js) 使用mqtt接收数据的代码如下所示:(Node.js)

var mqtt=require('mqtt');
var client=mqtt.connect('mqtt://test.mosquitto.org:1883');
var data;
client.subscribe('tempMeasurement');
client.on('message',function(topic,payload){
//arg=JSON.stringify(arg);
console.log("In Message......");
var tempStruct = JSON.parse(payload);
console.log("tempValue: "+tempStruct.tempValue); 
 });

Snapshot for error is shown below: 错误快照如下所示: 来自Node.js控制台的错误

MQTT message payloads are just byte arrays so you need to be aware of how a message is encoded at both the sending and receiving end. MQTT消息有效负载只是字节数组,因此您需要了解消息在发送和接收端如何进行编码。 In this case it is not clear exactly what you are sending as the code you have posted is just passing a Java Object. 在这种情况下,由于发布的代码只是传递Java对象,因此不清楚发送的是什么。

The error message in the picture implies that the a Java serialized version of the object is being sent as the message payload. 图片中的错误消息表示该对象的Java序列化版本正在作为消息有效负载发送。 While this will contain the information you need reassembling it in JavaScript will be incredibly difficult. 尽管其中将包含您需要的信息,但是使用JavaScript对其进行重组将非常困难。

Assuming the TempStruct object looks something like this: 假设TempStruct对象看起来像这样:

public class TempStruct {

  int value = 0;
  String units = "C";

  public void setValue(int val) {
    value = val;
  }

  public int getValue() {
    return value;
  }

  public void setUnits(String unit) {
    units = unit;
  }

  public String getUnits() {
    return units;
  }
}

Then you should add the following method: 然后,您应该添加以下方法:

public String toJSON() {
  String json = String.format("{'value': %d, 'units': '%s'}", value, units);
  return json;
}

Then edit your Java publishing code as follows: 然后,按如下所示编辑Java发布代码:

...
 this.myPubSubMiddleware.publish("tempMeasurement", newValue.toJSON().getBytes("utf-8"),
            myDeviceInfo);
...

And change your JavaScript like this: 然后像这样更改您的JavaScript:

...
client.on('message',function(topic,payload){
  console.log("In messgage....");
  var tempStruct = JSON.parse(payload.payloadString)
  console.log("tempValue: "+tempStruct.value);        
});
...

EDIT: 编辑:

Added getBytes("utf-8") to the Java code to ensure we are just putting the string bytes in the message. 在Java代码中添加了getBytes(“ utf-8”)以确保我们只是将字符串字节放入消息中。

EDIT2: Sorry, mixed up the paho web client with the npm mqtt module, the JavaScript should be: EDIT2:对不起,将Paho Web客户端与npm mqtt模块混合在一起,JavaScript应该是:

...
client.on('message',function(topic,payload){
  console.log("In messgage....");
  var tempStruct = JSON.parse(payload.toString())
  console.log("tempValue: "+tempStruct.value);        
});
...

Finally i am able to solve the problem.On the receiving side, we need to convert byte in to readable string and than parse readable using JSON parser. 最后我能够解决问题。在接收端,我们需要将字节转换为可读字符串,然后使用JSON解析器解析可读文件。 Solution is shown below: 解决方案如下所示:

var mqtt=require('mqtt');
var client=mqtt.connect('mqtt://test.mosquitto.org:1883');  
client.subscribe('tempMeasurement');
client.on('message',function(topic,payload){
if(topic.toString()=="tempMeasurement"){
console.log("Message received");
var data =payload.toString('utf8',7);
var temp=JSON.parse(data);
console.log(temp.tempValue,temp.unitOfMeasurement);
//console.log(data);
}  
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM