Nestjs中使用MQTT

准备工作,首先就得硬件的小伙伴自己吧硬件部分配置好,成功连通云端,并成功推送数据。然后就是服务器装好Nestjs 。做好这些准备工作就可以开始了!!!

然后直接开始工作:

一、安装 

# 直接安装最新的mqtt 我当前使用的5.5版本
yarn add mqtt

二、创建mqtt模块

# 生成 mqtt Module
nest g mo mqtt

# 生成 mqtt Service
nest g s mqtt

三、使用

import { Injectable, OnModuleInit } from '@nestjs/common';
import { connect } from 'mqtt';

@Injectable()
export class MqttService implements OnModuleInit {
    private mqttClient;

    onModuleInit() {
        this.mqttClient = connect('ws://broker.emqx.io:8083/mqtt', {
            clean: true,
            connectTimeout: 5000,
            clientId: 'mqtt-client-1',
            username: 'your-username',
            password: 'your-password',
            reconnectPeriod: 3000,
        })

        this.mqttClient.subscribe('/mysmarthome/pub') // 注意:这里必须选择自己需要订阅的toPic,否则就不会获取到数据

        this.mqttClient.on('connect', () => {
            console.log('MQTT连接成功!');
        })

        this.mqttClient.on('message', (topic, message) => {
            console.log(`${topic}: ${message.toString()}`);
        })

        this.mqttClient.on('error', (error) => {
            console.error('连接失败!', error);
        })
    }


    publish(topic: string, message: string) {
        this.mqttClient.publish(topic, message);
    }
}

到这里就差不都了,如果需要做大屏数据,可以采用websocket去做订阅和发布,大家根据自己的实际逻辑来就行了。 

 

 

相关推荐

  1. nestjs使用redis

    2024-04-07 12:06:01       47 阅读
  2. 在Android使用 MQTT 服务实现消息通信

    2024-04-07 12:06:01       10 阅读
  3. Flutter之MQTT使用

    2024-04-07 12:06:01       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-07 12:06:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-07 12:06:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-07 12:06:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-07 12:06:01       20 阅读

热门阅读

  1. 用FPGA搞图像算法需要具备哪些基础

    2024-04-07 12:06:01       12 阅读
  2. 手写一个民用Tomcat (02)

    2024-04-07 12:06:01       15 阅读
  3. 计算机网络的分层结构及模型

    2024-04-07 12:06:01       16 阅读
  4. 设计模式面试题(六)

    2024-04-07 12:06:01       15 阅读
  5. 当发生缓存未命中时,主存访问时间包括

    2024-04-07 12:06:01       12 阅读
  6. go实现生产者和消费者

    2024-04-07 12:06:01       15 阅读
  7. 腾讯光子工作室群 一面 (30min)

    2024-04-07 12:06:01       16 阅读