vue中使用Mqtt实现在线聊天

安装插件

npm install mqtt --save

设置(后台帮助订阅topic)

import { GlobalStore } from "@/store";
import mqtt, { IConnectPacket, MqttClient, Packet } from "mqtt";
import { computed } from "vue";

export interface MqttMsgHander {
  (message: string): void;
}

export default class MqttService {
  static BASE_URL = "xxxx";

  private static instance: MqttService = new MqttService();

  public static getInstance(): MqttService {
    return MqttService.instance;
  }

  // 客户端id
  static CLIENTID = computed(
    () => `${GlobalStore.getInstance().userMess.username}_web`
  );

  private listener: Map<string, Array<MqttMsgHander>> = new Map();

  private mqtt: MqttClient | null = null;

  token = computed(
    () =>
      sessionStorage.getItem("accessToken") ||
      localStorage.getItem("accessToken")
  );

  connect(username: string) {
    const option = {
      clientId: `${username}_web`,
      username: username,
      password: this.token.value!,
      keepalive: 60,
      clean: true,
      reconnectPeriod: 1000
    };
    this.mqtt = mqtt.connect(MqttService.BASE_URL, option);
    this.mqtt.once("connect", (topic: IConnectPacket) => {
      this.connectionOkHandler();
    });
  }

  disconnection() {
    this.mqtt!.end(true);
  }

  sendMsg(topic: string, mess: string) {
    return new Promise((resolve, reject) => {
      this.mqtt!.publish(topic, mess, (err?: Error, tas?: Packet) => {
        if (err) {
          reject(err);
        } else {
          resolve(0);
        }
      });
    });
  }

  connectionOkHandler() {
    this.mqtt!.on("message", (topic: string, message: any, packet: any) => {
      const sub = this.listener.get(topic);
      if (sub) {
        sub.forEach(sub => {
          sub(message);
        });
      }
    });
  }

  regirest(topic: string, handler: MqttMsgHander) {
    let handlers = this.listener.get(topic);
    if (!handlers) {
      handlers = new Array<MqttMsgHander>();
      this.listener.set(topic, handlers);
    }

    handlers.push(handler);
  }

  unregist(topic: string, handler: MqttMsgHander) {
    const handlers = this.listener.get(topic);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index > -1) {
        handlers.splice(index, 1);
      }
    }
  }
}

登录Mqtt

MqttService.getInstance().connect(username!);

使用

this.mqttInstance.regirest(
	this.topicMess.value.topic,
	this.receptionMessage
	);
  receptionMessage = (message?: any) => {
    const res = JSON.parse(message.toString());
    this.handleAvatar(res);
    this.modal.messageList.push(this.handleMess(res, false));
  };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值