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 ブローカーに wss で接続

Last updated at Posted at 2025-02-12

ブローカー 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'
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?