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

标签 node.js mqtt protocol-buffers

我有一个 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/

相关文章:

javascript - 同时向同一路由发出两个不同的 POST 请求

mqtt - ESP32 - 使用 MicroPython 的 MQTT 到 AWS IoT

java - MQTT 订阅数小时后未收到消息

go - 如何使用 Go 要求 protoc 使用值而不是指针作为映射的值侧?

c++ - 在 C/C++ 中使用 ProtoBuf 进行深度复制

node.js - Express、React、Node.js POST 路由 404 未找到

android - 无法使用 `phonegap plugin add XXX` 添加插件

c# - 异步Telnet服务器数据接收问题

javascript - 解析服务器 server.js 邮件适配器中的用户字段为空

java - 使用 Spring Integration MQTT 通过相同连接发布和订阅