uni-app与Node.js通信(MQTT)uni-app安装uni-socket.io
npm i @hyoga/uni-socket.io --save
使⽤
main.js
import io from'@hyoga/uni-socket.io';
const socket =io('你的域名',{
query:{},
transports:['websocket','polling'],
timeout:5000,
});
Vue.prototype.$socket = socket;
全局监听
App.vue
onShow:function(options){
console.log('App Show')
// console.log("[onShow] 本次场景值:", options.scene)
this.$("mqttMsg",(res)=>{
uni.$emit("mqttMsg", res);
})
},
page的页⾯⽂件,发送信息⾄Node.js
this.$it("send",{
"theme":"XXXXX"+ res.data.data.theme,
"mqttData": mqttData
})
Node.js
如果不懂此,请参考我的另外两个博客
创建 index.js
var net =require('net');
var express =require('express');
var app =express();
var server = ateServer()
var fs =require("fs")
var os =require("os");
var path =require("path");
var WebsocketMqtt =require('./WebsocketMqtt.js')
//页⾯实时更新的连接,全局
var RealTimeUpdateSocket =require("./RealTimeUpdateSocket.js")
//与⽹页的连接开始
var http =require("http").createServer(app)
var io =require('socket.io')(http)
//监听uni-app页⾯的连接
<('connection',function(socket){
RealTimeUpdateSocket.RealTimeUpdateSocket[socket.id]= socket
/
/新加⼊⼀个连接
<('setRoom',function(data){
console.log(socket.id)
// console.log(socket.id);
var name = Id;
网页app// 储存上线的⽤户
hashName[name +'']= socket.id
console.log(hashName)
})
//监听uni-app发送的信息
<("send",function(data){
WebsocketMqtt.sendMqttMsg(data.theme, data.mqttData);
})
//断开事件
<('disconnect',function(data){
console.log('断开', data)
RealTimeUpdateSocket.RealTimeUpdateSocket.splice(data.id,1)
console.log(RealTimeUpdateSocket.RealTimeUpdateSocket.length)
// it('c_leave', '离开');
//socket.broadcast⽤于向整个⽹络⼴播(除⾃⼰之外)
it('c_leave','某某⼈离开了')
})
})
//socket长连接结束
app.all('*',function(req, res, next){
// 解决跨域
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Headers","X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type","application/json;charset=utf-8");
next()
})
//设置消费结束
<('/setOver',function(req, res){
console.log(555)
})
http.listen(8083,function(){
var host = http.address().address
var port = http.address().port
console.log("应⽤实例,访问地址为 %s:%s", host, port)
})
//与⽹页的连接结束
WebsocketMqtt.js
const mqtt =require('mqtt')
/
/页⾯实时更新的连接,全局
var RealTimeUpdateSocket =require("./RealTimeUpdateSocket.js")
var randomCount = il(Math.random()*9999)+""+ Date.parse(new Date());; console.log(randomCount);
// 连接选项
const options ={
connectTimeout:4000,// 超时时间
// clientId: 'emqx-connect-via-websocket' + randomCount,
lientId:'xxxxxx',
username:'xxxxx',
password:'xxxx',
}
var client;
client = t('ws://你的域名/mqtt', options);
<('reconnect',(error)=>{
console.log('正在重连:', error)
})
<('error',(error)=>{
console.log('连接失败:', error)
})
<('connect',(e)=>{
console.log('成功连接服务器')
// 订阅主题下⾯的#是订阅XXXXX下⾯的所有主题
client.subscribe('xxxxx/#',{
qos:1
},(error)=>{
if(!error){
console.log('订阅成功')
// client.publish('xxxxxx', 'Hello EMQ', {
//  qos: 1,
//  rein: false
// }, (error) => {
//  console.log(error || '发布成功')
// })
}
})
})
<('message',(topic, message)=>{
console.log('收到来⾃', topic,'的消息', String())
var data =JSON.String());
// uni.$emit('MqttMsg',data);
//将收到的MQTT信息通过emit发送⾄uni-app页⾯
for(var item in RealTimeUpdateSocket.RealTimeUpdateSocket){
RealTimeUpdateSocket.RealTimeUpdateSocket[item].emit("mqttMsg", data); }
})
/
/发送信息到Mqtt
/*
jsonData:发送的数据
theme: 发送的主题
*/
var sendMqttMsg=function(theme, jsonData){
client.publish(theme,JSON.stringify(jsonData),{
qos:1,
rein:false
},(error)=>{
if(!error){
}
console.log(error ||'发布成功')
})
}
client: client,
sendMqttMsg: sendMqttMsg, }
通信介质RealTimeUpdateSocket.js //页⾯实时更新的连接,全局var RealTimeUpdateSocket =[]
RealTimeUpdateSocket
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。