我正在使用以下java代码来解包数据。但我不知道我怎么能为Node.js写同样的东西? Java代码如下所示:
public void receiveEvent(String forTopic, MqttMessage event)
throws MqttException {
Object obj = null;
java.io.ByteArrayInputStream bstream = new java.io.ByteArrayInputStream(
event.getPayload());
try {
java.io.ObjectInputStream st = new java.io.ObjectInputStream(
bstream);
obj = st.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataWrapper dt = (DataWrapper) obj;
s.notifyReceived(forTopic, dt.getObject(), dt.getDevice());
数据包装器的代码如下所示:
public class DataWrapper implements Serializable {
private static final long serialVersionUID = 1L;
Device device;
Object object;
public void setDevice(Device deviceInfo) {
this.device = deviceInfo;
}
public void setObject(Object object) {
this.object = object;
}
public Device getDevice() {
return device;
}
public Object getObject() {
return object;
}
}
答案 0 :(得分:2)
您可能想要查看MQTT.js.它可以在NPM上找到:https://www.npmjs.com/package/mqtt
举一个完整的例子,我们需要更多地了解您的设置以及您尝试做的事情......但这里是从MQTT复制的示例,js < / p>
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org');
client.on('connect', function () {
client.subscribe('presence');
client.publish('presence', 'Hello mqtt');
});
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
client.end();
});
它可能非常接近你想要的开始。