ブローカー wss://broker.hivemq.com:8884/mqtt
トピック testaa/topic
Publish
publish.js
const mqtt = require('mqtt')
// WebSocket エンドポイント
const brokerUrl = 'wss://broker.hivemq.com:8884/mqtt'
// MQTT クライアントの作成
const client = mqtt.connect(brokerUrl)
client.on('connect', () => {
console.log('Connected to MQTT broker')
// メッセージをパブリッシュ
const message = 'Good Afternoon Feb/12/2025'
client.publish('testaa/topic', message, (err) => {
if (!err) {
console.log('Message published')
} else {
console.error('Publish error:', err)
}
client.end() // 接続を閉じる
})
})
client.on('error', (err) => {
console.error('Connection error:', err)
})
実行コマンド
export NODE_PATH=/usr/lib/node_modules
node publish.js
Subscribe
subscribe.js
const mqtt = require('mqtt');
// WebSocket エンドポイント
const brokerUrl = 'wss://broker.hivemq.com:8884/mqtt'
// MQTT クライアントの作成
const client = mqtt.connect(brokerUrl)
client.on('connect', () => {
console.log('Connected to MQTT broker')
// トピックをサブスクライブ
client.subscribe('testaa/topic', (err) => {
if (!err) {
console.log('Subscribed to testaa/topic')
}
})
})
client.on('message', (topic, message) => {
console.log(`Received message on ${topic}: ${message.toString()}`)
})
client.on('error', (err) => {
console.error('Connection error:', err)
})
実行コマンド
export NODE_PATH=/usr/lib/node_modules
node subscribe.js
他の パブリック MQTT ブローカー
次でも確認しました。
const brokerUrl = 'wss://mqtt.eclipseprojects.io:443/mqtt'