nodejs zmq - полученные данные буфера, чем фактическое сообщение - PullRequest
2 голосов
/ 02 апреля 2020

Я делаю пример pubsub из этой ссылки и сумел заставить ее работать.

сервер. 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>

Is это нормально? или есть способ вернуть мое сообщение в string форме?

1 Ответ

2 голосов
/ 02 апреля 2020

Вы хотите преобразовать буфер в строку с toString() (по умолчанию utf-8 кодировка)

или вы можете использовать string-decoder из nodejs

с stringDecoder.write(buffer)

т.е. stringDecoder.write(topic)

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