프로젝트 환경
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
'네트워크 > MQTT' 카테고리의 다른 글
[MQTT] 5. Certification 확인 (문제 발생시만 확인) (0) | 2025.02.14 |
---|---|
[MQTT] 4. MQTT Arduino (0) | 2025.02.07 |
[MQTT] 2. mosquitto-auth-plug 셋업 (0) | 2025.01.24 |
[MQTT] 1. Mosquitto 셋업 (0) | 2025.01.17 |