こちらで立てたブローカーを使います。
MQTT over WebSocket: localhost でのテスト
Publish
pub_8083.js
const mqtt = require('mqtt')
// MQTTブローカーに接続
const client = mqtt.connect('mqtt://localhost:8083')
client.on('connect', () => {
console.log('Connected to MQTT broker')
// メッセージをパブリッシュ
client.publish('example/testTopic', 'Good Evening Everybody', (err) => {
if (err) {
console.error('Failed to publish message:', err)
} else {
console.log('Message published')
}
// 接続を閉じる
client.end()
})
})
client.on('error', (err) => {
console.error('Connection error:', err)
})
実行結果
$ node pub_8083.js
Connected to MQTT broker
Message published
Subscribe
sub_8083.js
const mqtt = require('mqtt')
// MQTTブローカーに接続
const client = mqtt.connect('mqtt://localhost:8083')
client.on('connect', () => {
console.log('Connected to MQTT broker')
// トピックをサブスクライブ
client.subscribe('example/testTopic', (err) => {
if (err) {
console.error('Failed to subscribe to topic:', err)
} else {
console.log('Subscribed to topic: example/testTopic')
}
})
})
// メッセージを受信したときの処理
client.on('message', (topic, message) => {
console.log(`Received message on topic "${topic}": ${message.toString()}`)
})
client.on('error', (err) => {
console.error('Connection error:', err)
})
実行結果
$ node sub_8083.js
Connected to MQTT broker
Subscribed to topic: example/testTopic
Received message on topic "example/testTopic": Good Evening Everybody
確認したバージョン
$ node --version
v23.7.0