【支付宝小程序】MQTT.js

【支付宝小程序】MQTT.js

参数配置

		//mqtt参数配置
		this.data = {
			client: null,
			host: "mqtt.server.com",
			subTopic: "Hello/",
			pubTopic: "Hello/",
			pubMsg: "Hello! I am from Alipay miniprogram",
			receivedMsg: "",
			mqttOptions: {
				username: "user",
				password: "password",
				reconnectPeriod: 1000, // 1000毫秒,设置为 0 禁用自动重连,两次重新连接之间的间隔时间
				connectTimeout: 5 * 1000, // 30秒,连接超时时间
				keepalive: 5,
				// 更多参数请参阅 MQTT.js 官网文档:https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
				// 更多 EMQ 相关 MQTT 使用教程可在 EMQ 官方博客中进行搜索:https://www.emqx.com/zh/blog

				//支付宝这里一定要传my
				// #ifdef MP-ALIPAY
				my: my,
				// #endif
			},

使用示例

connect(mqtt, url, subTopic) 
{
		try {
			console.log("conenctBtnText", "连接中...");
			const clientId = new Date().getTime();
			this.data.subTopic = subTopic
			this.data.pubTopic = subTopic
			this.data.server = url

			let server = `wss://${url}:8084/mqtt`
			//支付宝格式
			// #ifdef MP-ALIPAY
			server = `alis://${url}:8084/mqtt/`
			// #endif

			//微信格式
			// #ifdef MP-WEIXIN
			server = `wxs://${url}:8084/mqtt`
			// #endif

			console.log("conenct...", server);

			this.data.client = mqtt.connect(server, {
				...this.data.mqttOptions,
				clientId,
			});

			this.data.client.on("connect", () => {
				console.log("conenctBtnText", "连接成功");
				
				this.data.client.on("message", (topic, payload) => {
					//接收数据
					const currMsg = this.data.receivedMsg ? `<br/>${payload}` : payload;
					console.log("receivedMsg", this.data.receivedMsg.concat(currMsg));
				});

				this.data.client.on("error", (error) => {
					console.log("conenctBtnText", "连接");
					console.log("onError", error);
				});

				this.data.client.on("reconnect", () => {
					console.log("conenctBtnText", "正在重连接");
					console.log("reconnecting...");
				});

				this.data.client.on("offline", () => {
					console.log("conenctBtnText", "连接");
					console.log("onOffline");
				});
				
				// 更多 MQTT.js 相关 API 请参阅 https://github.com/mqttjs/MQTT.js#api

				//订阅主题
				if (this.data.client) {
					this.data.client.subscribe(subTopic, '{qos: 2}')
					console.log(`成功订阅主题:${this.data.subTopic}`);
					uni.showToast({
						title: '欢迎光临',
						icon: 'none',
						duration: 300
					});
					return
				}


			});
		} catch (error) {
			console.log("conenctBtnText", "连接");
			console.log("mqtt.connect error", error);
		}
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值