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去做订阅和发布,大家根据自己的实际逻辑来就行了。 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值