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: ブラウザーで接続

Posted at

こちらで設定した mosquitto のサーバーに接続する方法です。
MQTT over WebSocket: localhost でのテスト

ページ

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MQTT WebSocket クライアント</title>
  <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
  <h1>MQTT WebSocket クライアント</h1>
  <div id="status"></div>
  <script>
    // MQTT.js を使って接続
    const client = mqtt.connect('ws://127.0.0.1:8080'); // または 'ws://localhost:8083'

    client.on('connect', () => {
      document.getElementById('status').innerText = '接続成功!';
      console.log('MQTT 接続成功');
    });

    client.on('error', (err) => {
      document.getElementById('status').innerText = '接続失敗';
      console.error('MQTT 接続エラー:', err);
    });

    // メッセージの購読
    client.subscribe('example/testTopic', (err) => {
      if (!err) {
        client.publish('example/testTopic', 'Hello MQTT from Browser!');
      }
    });

    // メッセージを受け取ったときの処理
    client.on('message', (topic, message) => {
      console.log('メッセージ受信:', topic, message.toString());
    });
  </script>
<hr />
<p>Feb/10/2025</p>
</body>
</html>

サーバーの起動

http-server

サブスクライブ

mqtt sub -t 'example/testTopic' -h 'localhost' -p 8083 -v

ブラウザーで、 http://127.0.0.1:8081 にアクセス
image.png

$ mqtt sub -t 'example/testTopic' -h 'localhost' -p 8083 -v
example/testTopic Hello MQTT from Browser!

image.png

コマンドラインで Publish

mqtt pub -t 'example/testTopic' -h 'localhost' -p 8083 -m 'Good Afternoon'

コンソールにメッセージが表示される

image.png

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?