개발 노트

mqtt연결 시 connected반복 에러 본문

React

mqtt연결 시 connected반복 에러

한츄 2024. 2. 28. 17:33

mqtt - npm (npmjs.com)

 

mqtt

A library for the MQTT protocol. Latest version: 5.3.6, last published: 2 days ago. Start using mqtt in your project by running `npm i mqtt`. There are 2650 other projects in the npm registry using mqtt.

www.npmjs.com

import { count, log } from 'console';
import mqtt, { MqttClient } from 'mqtt';

const mqttUri = 'ws://127.0.0.1:9001';

const options: mqtt.IClientOptions = {
//clientId는 고유 식별자로 지정할 것!!필수!!
  clientId: `nextjs`+ + Math.random().toString(16).substr(2, 8),
  reconnectPeriod: 1000,
  keepalive: 120,
  clean: true,
};

let client: MqttClient | undefined;

self.addEventListener('message', (e) => {
  console.log(e.data);
  
  if (e.data.CMD === 'MQTT_START') {
    // 'MQTT_START' 명령을 받았을 때, 이미 연결된 클라이언트를 재사용
    if (!client || (client && client.connected === false)) {
      console.count('test')
      client = mqtt.connect(mqttUri, options);
      client.on('connect', () => {
        console.count('connected-');
        console.log('connected');
      });
      client.on('disconnect', (packet) => {
        console.log('disconnected', packet);
      });
      client.on('error', (error) => {
        postMessage('Error: ' + error.message);
      });
      client.on('message', (topic, message) => {
        postMessage({ topic: topic, message: message.toString() });
      });
      // client.reconnect();
    }
  }

  if (e.data.CMD === 'MQTT_STOP' && client) {
    client.end();
  }

  if (e.data.CMD === 'MQTT_SUBSCIBE' && client) {
    client.subscribe(e.data.DATA);
  }
});

 

 

clientId를 고유식별자로 지정하지않아서 생기는 문제였다..