nodejs zmq-接收到的缓冲区数据比实际消息多

问题描述 投票:1回答:1

我正在以pubsub中的this link为例,并设法使其正常工作。

server.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()

client.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形式取回我的消息?

node.js zeromq
1个回答
1
投票

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

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()
© www.soinside.com 2019 - 2024. All rights reserved.