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 over WebSocket: MQTT.js で接続

Posted at

こちらで立てたブローカーを使います。
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
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?