gpt4 book ai didi

node.js - 如何使用 nodeJS 和 protobufjs 在 MQTT 中发送缓冲区或字节数组

转载 作者:搜寻专家 更新时间:2023-11-01 00:08:24 25 4
gpt4 key购买 nike

我有一个 nodejs (node v0.10.26) MQTT 代码,它将字符串发布到远程 MQTT 服务器上的主题。现在我试图将一个字节数组和一个缓冲区发布到同一主题,但出现错误代码:

var ProtoBuf = require("protobufjs");
var mqtt = require('mqtt');
var builder = ProtoBuf.loadProtoFile('event.proto'),
as2 = builder.build('as2'),
Message=as2.Message;

var message = new Message({
"message_type": "EMOTICON"
});
console.log("message : "+message);
var buffer_message= message.encode();
client = mqtt.createClient(1883,'hostNameOfMQTT',{ encoding: 'binary' });
client.publish('NewTopic',buffer_message);
client.on('connect', function() {
console.log("Message published : "+buffer_message);
client.end();
});

当我执行时出现这个错误node.exe sampleMqtt.js

C:\node>node.exe SimpleMQTT.js消息:.as2.消息

C:\node\node_modules\mqtt\lib\generate.js:178 length += Buffer.byteLength(payload);

                 ^
TypeError: Argument must be a string
at Object.module.exports.publish (C:\node\node_modules\mqtt\lib\
generate.js:178:22)
at Connection.eval [as publish] (eval at <anonymous> (C:\node\no
de_modules\mqtt\lib\connection.js:58:29), <anonymous>:2:26)
at MqttClient._sendPacket (C:\node\node_modules\mqtt\lib\client.
js:430:20)
at MqttClient.<anonymous> (C:\node\node_modules\mqtt\lib\client.
js:105:12)
at MqttClient.EventEmitter.emit (events.js:117:20)
at MqttClient._handleConnack (C:\node\node_modules\mqtt\lib\clie
nt.js:498:10)
at Connection.<anonymous> (C:\node\node_modules\mqtt\lib\client.
js:191:10)
at Connection.EventEmitter.emit (events.js:95:17)
at Connection._write (C:\node\node_modules\mqtt\lib\connection.j
s:187:12)
at doWrite (_stream_writable.js:226:10)

然而,当我尝试发布 buffer_message.tostring() 时,我得到的是字符串形式的对象详细信息,而不是实际的 ArrayBuffer?client.publish('AnkitTopic',buffer_message.toString());使用 toString() -> ByteBuffer(offser=0,markedOffSet=-1,length=2,capacity=16) 输出

我不想要一个字符串,我想要通过 MQTT 传输实际的 byteBuffer。

有人,请建议我该怎么做!!我猜它不太难得到,在 java 中是可能的,那为什么不在 nodeJS 中呢?

最佳答案

您能否尝试发送另一种二进制内容(例如文件)以查看其是否有效?

最新的 MQTT.js 版本支持二进制负载 https://github.com/adamvr/MQTT.js/issues/109

关于node.js - 如何使用 nodeJS 和 protobufjs 在 MQTT 中发送缓冲区或字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com