네트워크/MQTT

[MQTT] 3. MQTT Node.js

IT 기술자 2025. 1. 31. 11:00

프로젝트 환경

1. 프로젝트 폴더 생성 후 이동
ex) cd mqtt-test

 

2. mqtt 모듈 세팅

yarn
yarn add mqtt

 

3. 인증 파일을 프로젝트 폴더로 복사

ca.crt
server.crt
server.key

 

4. subscriber 생성 후 실행

mqtt-receiver.js

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

const KEY = fs.readFileSync(path.join(__dirname, '/server.key'))
const CERT = fs.readFileSync(path.join(__dirname, '/server.crt'))
const TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, '/ca.crt'))

const PORT = 8883
const HOST = '[ip/domain]'

const options = {
  port: PORT,
  host: HOST,
  key: KEY,
  cert: CERT,
  rejectUnauthorized: false,
  ca: TRUSTED_CA_LIST,
  protocol: 'mqtts',
  username: '[username]',
  password: '[pw]'
};
const client = mqtt.connect(options);

client.on('connect', function () {
  client.subscribe('[topic]', function (err) {
    if (!err) {
      console.log('Receiver Connect!');
    }
  })
});

client.on('message', function (topic, message) {
  console.log(message.toString())
})

 

예) ip/domain : 192.168.1.101, username : korea_company, pw : korea_company , topic : test/topic

node mqtt-receiver.js

 

5. publisher 생성 후 실행

mqtt-sender.js

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

const KEY = fs.readFileSync(path.join(__dirname, '/server.key'))
const CERT = fs.readFileSync(path.join(__dirname, '/server.crt'))
const TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, '/ca.crt'))

const PORT = 8883
const HOST = '[ip/domain]'

const options = {
  port: PORT,
  host: HOST,
  key: KEY,
  cert: CERT,
  rejectUnauthorized: false,
  ca: TRUSTED_CA_LIST,
  protocol: 'mqtts',
  username: '[username]',
  password: '[pw]'
};
const client = mqtt.connect(options);

client.on('connect', function () {
  client.subscribe('test/topic', function (err) {
    if (!err) {
      console.log('Sender Connect!');
      client.publish('test/topic', 'Hello nodejs');
    }
    client.end();
  })
})

예) ip/domain : 192.168.1.101, username : korea_company , pw : korea_company , topic : test/topic

node mqtt-sender.js