【Node.js】Node.jsでMQTTを使ってみる

 前回構築したMQTT Broker の通信確認のためにNode.jsでMQTTの通信するコードを組みました。

 完成しているソースは下記にあります。

nodejs-sample/mqtt at main · tsuneken5/nodejs-sample
Contribute to tsuneken5/nodejs-sample development by creating an account on GitHub.

環境

 以下の環境で動作確認しています。

  • ホストOS:Windows 11
  • ゲストOS:Ubuntu 20.04.5
  • Node:18.13.0

プロジェクトの作成

$ npm init

ライブラリのインストール

 ライブラリは MQTT.js を使用します。

$ npm install mqtt

共通部分

const mqtt = require('mqtt');
const fs = require('fs');

const base_topic = 'test-topic';
connectTCP();
connectWebsocket();
connectTLS();
connectSecureWebsocket();

 MQTT.jsクライアントライブラリとfsモジュールをインポートします。fsはTLS/SSL通信時の証明書を読み込むため。

TCP

function connectTCP() {
  const protocol = 'mqtt';
  const host = 'localhost';
  const port = '1883';
  const connectUrl = `${protocol}://${host}:${port}`;
  const clientId = `mqtt_${Math.random().toString(16).slice(3)}`;
  const topic = base_topic + '/tcp';

  console.log('TCP connect client id :', clientId);
  const client = mqtt.connect(connectUrl, {
    clientId,
    connectTimeout: 4000
  });

  client.on('connect', () => {
    client.subscribe(topic, (error) => {
      if (!error) {
        client.publish(topic, 'TPC')
      }
    });
  });


  client.on('message', (topic, message) => {
    console.log('subscribe to', message.toString());
    client.end();
  });
}

 基本的な接続方法。

 MQTTと接続するために、プロトコル、ホスト、ポート番号、クライアントIDを設定します。ポート番号はMQTT Brokerの設定に合わせて変更してください。

 mqtt.connect() でMQTT Brokerに接続します。

 client.on('connect') で接続ステータスを監視し、接続成功後の client.subscribe(topic) でtopicを監視します。今回トピックは一つのみですが、複数のトピックを関ししたい場合はそれぞれのトピックで client.subscribe(topic) を記載する必要があります。

 接続完了後、 client.publish(topic, message) でメッセージをパブリッシュします。

 メッセージをサブスクライブしたときの処理は client.on('message') で定義します。今回はメッセージを出力して client.end() で切断しています。

WebSocket

function connectWebsocket() {
  const protocol = 'ws';
  const host = 'localhost';
  const port = '8083';
  const path = '';
  const connectUrl = `${protocol}://${host}:${port}${path}`;
  const clientId = `mqtt_${Math.random().toString(16).slice(3)}`;
  const topic = base_topic + '/websocket';

  console.log('WebSocket connect client id :', clientId);
  const client = mqtt.connect(connectUrl, {
    clientId,
    connectTimeout: 4000,
  });

  client.on('connect', () => {
    client.subscribe(topic, (error) => {
      if (!error) {
        client.publish(topic, 'WebSocket')
      }
    });
  });


  client.on('message', (topic, message) => {
    console.log('subscribe to', message.toString());
    client.end();
  });
}

 TCPの場合から変更するのはプロトコルとポート番号のみです。

TLS/SSL

function connectTLS() {
  const protocol = 'mqtts';
  const host = 'localhost';
  const port = '8883';
  const connectUrl = `${protocol}://${host}:${port}`;
  const clientId = `mqtt_${Math.random().toString(16).slice(3)}`;
  const topic = base_topic + '/tls-ssl';

  console.log('TLS/SSL connect client id :', clientId);
  const client = mqtt.connect(connectUrl, {
    clientId,
    connectTimeout: 4000,
    // サーバーがCA証書を使用している場合は、CAを渡す
    ca: fs.readFileSync('./ssl/ca.crt'),
  });

  client.on('connect', () => {
    client.subscribe(topic, (error) => {
      if (!error) {
        client.publish(topic, 'TLS/SSL')
      }
    });
  });

  client.on('message', (topic, message) => {
    console.log('subscribe to', message.toString());
    client.end();
  });
}

 TLS/SSL通信の場合は、プロトコルとポート番号を変更する以外に、Brokerの設定によっては証明書を渡してやる必要があります。

Secure WebSocket

function connectSecureWebsocket() {
  const protocol = 'wss';
  const host = 'localhost';
  const port = '8084';
  const path = '';
  const connectUrl = `${protocol}://${host}:${port}${path}`;
  const clientId = `mqtt_${Math.random().toString(16).slice(3)}`;
  const topic = base_topic + '/secure-websocket';

  console.log('Secure WebSocket connect client id :', clientId);
  const client = mqtt.connect(connectUrl, {
    clientId,
    connectTimeout: 4000,
    // サーバーがCA証書を使用している場合は、CAを渡す
    ca: fs.readFileSync('./ssl/ca.crt'),
  });

  client.on('connect', () => {
    client.subscribe(topic, (error) => {
      if (!error) {
        client.publish(topic, 'Secure WebSocket')
      }
    });
  });

  client.on('message', (topic, message) => {
    console.log('subscribe to', message.toString());
    client.end();
  });
}

 TLS/SSLの場合と同じようにプロトコルとポート番号を変更して、証明書を渡してやります。

実行

 実行後、下記のように表示されればOKです。

$ node index.js 
TCP connect client id : mqtt_222335280084
WebSocket connect client id : mqtt_c0c586f55bec
TLS/SSL connect client id : mqtt_23b8d9c49102
Secure WebSocket connect client id : mqtt_8976b6b90392
subscribe to TLS/SSL
subscribe to WebSocket
subscribe to TPC
subscribe to Secure WebSocket

 Broker側のログは下記のようになります。

1725437881: New connection from 172.18.0.1:55760 on port 1883.
1725437881: New connection from 172.18.0.1:60450 on port 8883.
1725437881: New client connected from 172.18.0.1:55760 as mqtt_222335280084 (p2, c1, k60).
1725437881: New client connected from 172.18.0.1:60450 as mqtt_23b8d9c49102 (p2, c1, k60).
1725437881: New client connected from ::ffff:172.18.0.1:42534 as mqtt_c0c586f55bec (p2, c1, k60).
1725437881: New client connected from ::ffff:172.18.0.1:41738 as mqtt_8976b6b90392 (p2, c1, k60).
1725437881: Client mqtt_23b8d9c49102 disconnected.
1725437881: Client mqtt_c0c586f55bec disconnected.
1725437881: Client mqtt_222335280084 disconnected.
1725437881: Client mqtt_8976b6b90392 disconnected.

コメント

タイトルとURLをコピーしました