2025年5月23日金曜日

MQTT over WebSocketのクイックスタートガイド

mqttx gui版はdownload にあるsnap版をマウントして中のmqttxを実行 

https://qiita.com/emqx_japan/items/44494fe8ed29eb0c2521

MQTT over WebSocketのクイックスタートガイド


sample of index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket MQTT</title>
  <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
  WebSocketクライアントを使用してMQTTサーバーに接続する
</body>
<script>
    const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
    const host = 'ws://broker.emqx.io:8083/mqtt'
    const options = {
      keepalive: 60,
      clientId: clientId,
      protocolId: 'MQTT',
      protocolVersion: 4,
      clean: true,
      reconnectPeriod: 1000,
      connectTimeout: 30 * 1000,
      will: {
        topic: 'WillMsg',
        payload: 'Connection Closed abnormally..!',
        qos: 0,
        retain: false
      },
    }
    console.log('Connecting mqtt client')
    const client = mqtt.connect(host, options)
    client.on('error', (err) => {
      console.log('Connection error: ', err)
      client.end()
    })
    client.on('reconnect', () => {
      console.log('Reconnecting...')
    })
    client.on('connect', () => {
  console.log(`Client connected: ${clientId}`)
  // トピックをサブスクライブ
  client.subscribe('testtopic', { qos: 0 })
})
// トピックを解除
//client.unubscribe('testtopic', () => {
//  console.log('Unsubscribed');
//})
    // メッセージをパブリッシュ
client.publish('testtopic', 'ws connection demo...!', { qos: 0, retain: false })
// メッセージを受信
client.on('message', (topic, message, packet) => {
  console.log(`Received Message: ${message.toString()} On topic: ${topic}`)
})
</script>

0 件のコメント:

コメントを投稿