nodejs + uniapp 联合开发MQTT服务端与移动端app

服务端效果图:
在发布端用定时器模拟数据上传给服务端。
在这里插入图片描述
移动端效果图:
变化的数字是从发布端上传到服务端,再推送到移动端。
在这里插入图片描述

1. nodejs 安装MQTT服务

1.1 安装 mqtt 服务器必要依赖项 mosca mqtt

npm install mosca mqtt --save

1.2 在项目根目录下新建 server.js

const mosca = require("mosca");

//https密钥路径
// const SECURE_KEY=dirname+'/key.pem"
// const SECURE_CERT = dirname+"/cert.pem"

//设置参数
const mqttSetting  = {
    
    
  interfaces:[
	  {
    
     type: "mqtt", port: 1883 },
	  {
    
     type: "http", port: 3000, bundle: true }
	  //{ type: "mqtts", port: 8883, bundle: true, credentials: { keyPath: SECURE_KEY, certPath: SECURE_CERT } },
	  //{ type: "https", port: 1884, bundle: true, credentials: { keyPath: SECURE_KEY, certPath: SECURE_CERT } }
  ]
}

//实例化
const MqttServer = new mosca.Server(mqttSetting)

//开启服务
MqttServer.on("ready", function() {
    
    
	console.log("mqtt is running...");
});

//监听客户端连接
MqttServer.on("clientConnected", function(client) {
    
    	
	console.log("client connected", client.id);
});

//监听MQTT主题消息,当客户端发布主题消息时执行
MqttServer.on("published", function(packet, client) {
    
    
	var topic = packet.topic;
	switch (topic) {
    
    
		case "test_topic":
			console.log('message', packet.payload.toString());
			//MQTT可以转发主题消息至其他主题
			//MqttServer.publish({ topic: 'other', payload: 'sssss' });
		break;
		case "other":
			console.log("message_other", packet.payload.toString());
		break;
	}
});

2. 创建MQTT 发布端

在项目根目录下新建 publish.js

const mqtt = require("mqtt");

//连接到mqtt服务端
const client = mqtt.connect("mqtt://192.168.3.7:1883/mqtt"); 

//写个定时器定时每隔3秒定时推送天气信息,此业务可替换为自己的实际需求
setInterval(function() {
    
    
	const value = Math.ceil(Math.random() * 40);
	console.log('发布了:' + value)
	
	//发布主题为test_topic的消息
	client.publish("test_topic", value.toString(), {
    
    
		// QoS0,至多一次; QoS1,至少一次; QoS2,确保只有一次。
		qos: 0,  
		retain: true
	});

}, 3000);

3. 创建MQTT 订阅端

在项目根目录下新建 subscribe.js

const mqtt = require("mqtt");

//连接到mqtt服务端
const client = mqtt.connect("mqtt://192.168.3.7:1883/mqtt"); 

client.on("connect", function() {
    
    
	console.log("服务器连接成功");
	// connected = client.connected
	
	//订阅主题为test_topic的消息
	client.subscribe("test_topic", {
    
    
		qos: 1
	}); 
});

client.on("message", function(top, message) {
    
    
	console.log("当前topic:", top);
	console.log("当前温度:", message.toString());
});

4. 进入项目根目录依次运行服务端,发布端,订阅端

运行服务端报错 Expected schema to be an object or boolean 的解决方法:
点我看看
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5. 用uniapp编写移动端订阅

先下载mqtt.min.js到项目,打开网址后在页面 另存为…
https://unpkg.com/mqtt/dist/mqtt.min.js

uniapp 代码

<template>
	<view class="content">
		<image class="logo" src="/static/logo.png" @click="mqttsub()"></image>
		<view class="text-area">
			<view class="title">{
    
    {
    
    title}}</view>
		</view>
	</view>
</template>

<script>
	
	export default {
    
    
		data() {
    
    
			return {
    
    
				title: 'Hello'
			}
		},
		onLoad() {
    
    
			
		},
		methods: {
    
    
			mqttsub(){
    
    
				//引入js文件
				var mqtt = require('../../mqtt.min.js')
				var that = this
				
				// app端和小程序端必须用 wx://
				// **此处要使用http对应的端口,否则连接不上MQTT服务端
				var client = mqtt.connect('wx://192.168.3.7:3000/mqtt',{
    
    
					username:"guest",
					password:"guest"
				})
				
				client.on('connect', function() {
    
    
					console.log("已连接")
					//订阅test_topic主题
					client.subscribe("test_topic", function(err) {
    
    						
						if (!err) {
    
    
							//向test_topic主题发送消息
							client.publish("test_topic", '来自隔壁老王的消息')
						}else{
    
    
							console.log("订阅主题发生错误:"+err)
						}						
					})
					
				}).on('reconnect', function() {
    
    
					console.log("重连")
					
				}).on('error', function() {
    
    
					console.log("错误")
					
				}).on('end', function() {
    
    
					console.log("断开连接")
					
				}).on('message', function(topic, message) {
    
     //接收消息
					//app通知栏推送
					// plus.push.createMessage("您有新消息","可选-消息承载的数据",{
    
    
					// 	title:"测试成功"
					// })
					console.log('接收到的消息:' + message)
					that.title = message
					
					
				})
			}
		}
	}
</script>

<style>
	.content {
    
    
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
    
    
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
    
    
		display: flex;
		justify-content: center;
	}

	.title {
    
    
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

注意要点
在这里插入图片描述
在这里插入图片描述
参考文章:
uniapp+mqtt(RabbitMQ)实现消息推送
使用 nodejs 快速搭建 MQTT 服务器及实时推送、获取数据

おすすめ

転載: blog.csdn.net/weixin_38946164/article/details/119845136