0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MQTT.js: パブリック MQTT ブローカーの使い方

Posted at

Publish

pub01.js
const mqtt = require("mqtt")
// const host = "test.mosquitto.org"
const host = "broker.emqx.io"
const client = mqtt.connect("mqtt://" + host)

const topic_target = "test_topic/aaa"
client.on("connect", () => {
  client.subscribe(topic_target, (err) => {
    if (!err) {
      client.publish(topic_target, "Hello mqtt Feb/09/2025 PM 18:12")
  client.end()
    }
  })
})

実行コマンド

go_pub01.sh
export NODE_PATH=/usr/local/lib/node_modules
node pub01.js

Subscribe

sub01.js
const mqtt = require("mqtt")
// const host = "test.mosquitto.org"
const host = "broker.emqx.io"
const client = mqtt.connect("mqtt://" + host)

const topic_target = "test_topic/aaa"
client.on("connect", () => {
  client.subscribe(topic_target, (err) => {
    if (!err) {
	console.log("*** subscribed *** " + topic_target)
    }
  })
})

client.on("message", (topic, message) => {
  // message is Buffer
  console.log(topic.toString())
  console.log(message.toString())
//  client.end()
})

実行コマンド

go_sub01.sh
export NODE_PATH=/usr/local/lib/node_modules
node sub01.js

実行結果

$ ./go_sub01.sh 
*** subscribed *** test_topic/aaa
test_topic/aaa
Hello mqtt Feb/09/2025 PM 18:12
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?