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?

WebブラウザでパブリックMQTTサーバーに接続

Last updated at Posted at 2025-02-11

ブローカー ws://broker.hivemq.com:8000/mqtt

トピック testaa/topic

Subscribe

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MQTT Web Client</title>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
<h1>MQTT Web Client</h1>
<script>
        // MQTTブローカーのURL (WebSocket)
        const brokerUrl = 'ws://broker.hivemq.com:8000/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);
        });

        // 切断時のイベント
        client.on('close', () => {
            console.log('Connection closed');
        });
</script>
<hr />
<p>Feb/11/2025 PM 13:59</p>
</body>
</html>

Publish

publish.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MQTT Publish from Web</title>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
<h1>MQTT Publish from Web</h1>
<button id="publishButton">Publish Message</button>
<p id="status"></p>

    <script>
        // WebSocket エンドポイント
        const brokerUrl = 'ws://broker.hivemq.com:8000/mqtt';

        // MQTT クライアントの作成
        const client = mqtt.connect(brokerUrl);

        // 接続時のイベント
        client.on('connect', () => {
            console.log('Connected to MQTT broker');
            document.getElementById('status').innerText = 'Connected to MQTT broker';
        });

        // エラー時のイベント
        client.on('error', (err) => {
            console.error('Connection error:', err);
            document.getElementById('status').innerText = 'Connection error: ' + err.message;
        });

        // ボタンクリック時のイベント
        document.getElementById('publishButton').addEventListener('click', () => {
            const topic = 'testaa/topic'; // トピック名
            const message = 'Hello from Web Browser Feb/11/2025'; // メッセージ内容

            // メッセージをパブリッシュ
            client.publish(topic, message, (err) => {
                if (!err) {
                    console.log('Message published');
                    document.getElementById('status').innerText = `Published: ${message} to ${topic}`;
                } else {
                    console.error('Publish error:', err);
                    document.getElementById('status').innerText = 'Publish error: ' + err.message;
                }
            });
        });
    </script>
</body>
</html>

テスト

http-server

image.png

image.png

Node.js で確認

Publish

publish.js
const mqtt = require('mqtt');

// WebSocket エンドポイント
const brokerUrl = 'ws://broker.hivemq.com:8000/mqtt';

// MQTT クライアントの作成
const client = mqtt.connect(brokerUrl);

client.on('connect', () => {
  console.log('Connected to MQTT broker');

  // メッセージをパブリッシュ
  client.publish('testaa/topic', 'Good Afternoon from MQTT.js', (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 = 'ws://broker.hivemq.com:8000/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
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?