gpt4 book ai didi

node.js - nodejs zmq - 收到的缓冲区数据比实际消息

转载 作者:行者123 更新时间:2023-12-04 15:32:22 27 4
gpt4 key购买 nike

我正在做来自 this linkpubsub 示例并设法让它发挥作用。

服务器.js:

const zmq = require("zeromq")

async function run() {
const sock = new zmq.Publisher

await sock.bind("tcp://127.0.0.1:3000")
console.log("Publisher bound to port 3000")

while (true) {
console.log("sending a multipart message envelope")
await sock.send(["kitty cats", "meow!"])
await new Promise(resolve => setTimeout(resolve, 500))
}
}

run()

客户端.js:

const zmq = require("zeromq")

async function run() {
const sock = new zmq.Subscriber

sock.connect("tcp://127.0.0.1:3000")
sock.subscribe("kitty cats")
console.log("Subscriber connected to port 3000")

for await (const [topic, msg] of sock) {
console.log("received a message related to:", topic, "containing message:", msg)
}
}

run()

所以我希望来自 client.js 的日志是:

received a message related to: kitty cats containing message: meow!

但改用这个:

received a message related to: <Buffer 6b 69 74 74 79 20 63 61 74 73> containing message: <Buffer 6d 65 6f 77 21>

这正常吗?或者有没有办法以 string 形式取回我的消息?

最佳答案

您需要使用 toString() 将 Buffer 转换为字符串(默认为 utf-8 编码)

或者您可以使用 string-decoder来自 Node

使用 stringDecoder.write(buffer)

stringDecoder.write(主题)

const zmq = require("zeromq")

async function run() {
const sock = new zmq.Subscriber

sock.connect("tcp://127.0.0.1:3000")
sock.subscribe("kitty cats")
console.log("Subscriber connected to port 3000")

for await (const [topic, msg] of sock) {
console.log("received a message related to:", topic.toString("utf=8"), "containing message:", msg.toString("utf-8")
}
}

run()

关于node.js - nodejs zmq - 收到的缓冲区数据比实际消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60985737/

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