uniapp 微信小程序mqtt开发

2,532 阅读1分钟

微信小程序只支持https和wss,在这里用公开的mqtt服务器来做测试

wss://test.mosquitto.org 端口号8081

QQ截图20210513175151.png

客户端就用 支持浏览器访问的 MQTT 在线客户端工具,不用另外下载直接用浏览器打开就行了

1111116.png

测试工具准备好了,接下来就开始写代码了

mqtt的库就用 mqtt.js

1 安装mqtt.js

进入项目的目录

npm install mqtt@3.0.0 --save

这里用3.0.0版本的,4.0.0版本的也行,最新版本的在微信小程序里面连接不上服务器。

2 连接mqtt服务器
const options = {
	clientId: "mqtt_" + parseInt(Math.random() * 100 + 800, 10),
	port: 8081,
	keepalive: 60,
	clean: true,
	reconnectPeriod: 0,
	connectTimeout: 30 * 1000,
	protocolId: 'MQTT',
	protocolVersion: 4
};

// #ifdef H5
let url = 'wss://test.mosquitto.org'
// #endif
// #ifdef MP-WEIXIN||APP-PLUS
let url = 'wxs://test.mosquitto.org'
// #endif

let client = mqtt.connect(url, options)

//连接成功回调
client.on("connect", function() {
	that.isConnect = true;
	console.log("connect success!");
});

//异常回调
client.on("error", function(err) {
	console.log(err);
});

client.on("offline", function() {
	console.log("offline");
});

client.on("close", function() {
	console.log("close");
});

//收到消息的回调
client.on("message", function(topic, message) {
	console.log(`message = ${message.toString()}`);
});

完整的代码

<template>
	<view class="content">
		<!-- <image class="logo" src="/static/logo.png"></image> -->
		<text class="title">发布消息</text>
		<view class="br"></view>
		<view class="text-area">
			<text>Topic</text>
			<input class="edittext" v-model="publishTopic" />
		</view>
		<view class="br"></view>
		<view class="text-area">
			<text>Payload</text>
			<textarea class="edittext" v-model="publishMsg" />
		</view>
		<view class="br"></view>
		<button @click="publish">publish</button>

		<text class="title">订阅主题</text>
		<view class="text-area">
			<!-- 订阅 -->
			<input class="edittext" v-model="subscribeTopic" />
		</view>
		<view class="br"></view>
		<button @click="subscribe">subscribe</button>
		<view class="br"></view>
		<text class="title">收到的Message</text>
		<view class="br"></view>
		<view v-for="(item, index) in subList" :key="index">
			<text>Topic:{{ item.topic }} ,Payload: {{ item.msg }}</text>
		</view>
	</view>
</template>
import mqtt from 'mqtt/dist/mqtt.js'

	//let mqtt = require('mqtt/dist/mqtt.js')

	const options = {
		connectTimeout: 4000, // 超时时间
		clientId: "mqtt_" + parseInt(Math.random() * 100 + 800, 10),
		port: 8081,
	};
	
	// #ifdef H5
	let url = 'wss://test.mosquitto.org'
	// #endif
	// #ifdef MP-WEIXIN||APP-PLUS
	let url = 'wxs://test.mosquitto.org'
	// #endif

	let client = mqtt.connect(url, options)



	export default {
		data() {
			return {
				publishMsg: "",
				publishTopic: "",
				subscribeTopic: "",
				subList: [],
				isConnect: false,
			}
		},
		onLoad() {
			this.init();
		},
		created() {
			//this.init();
		},
		methods: {
			publish() {
				//发布消息
				if (this.isConnect) {
					client.publish(this.publishTopic, this.publishMsg, (err) => {
						if (err) {
							//alert(`发布消息失败`);
							uni.showToast({
								title: "发布消息失败",
								duration: 2000,
								icon: "none"
							})
						}
					});
				}
			},
			subscribe() {
				if (this.isConnect) {
					client.subscribe(this.subscribeTopic, (err) => {
						if (!err) {
							uni.showToast({
								title: `订阅${this.subscribeTopic}主题成功`,
								duration: 2000,
								icon: "none"
							})
						} else {
							uni.showToast({
								title: `订阅${this.subscribeTopic}主题失败`,
								duration: 2000,
								icon: "none"
							})
						}
					});
				}
			},
			init() {
				const that = this;

				//连接成功回调
				client.on("connect", function() {
					that.isConnect = true
					console.log("connect success!");
				});

				//异常回调
				client.on("error", function(err) {
					that.isConnect = false
					console.log(err);
				});
				
				client.on("offline", function() {
					that.isConnect = false
					console.log("offline");
				});
				
				client.on("close", function() {
					that.isConnect = false
					console.log("close");
				});

				//收到消息的回调
				client.on("message", function(topic, message) {
					console.log(`message = ${message.toString()}`);
					that.subList.push({
						topic: topic.toString(),
						msg: message.toString(),
					});
				});
			},
		}
	}

最后测试

ssssssss.png

pppppp.png

在Android真机和ios真机还是无法连接上服务器的,因为微信小程序有限制,具体mqtt服务器的接入可以参考这个

QQ截图20210513183059.png