赞
踩
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.$socket.on("mqttMsg", (res) => {
uni.$emit("mqttMsg", res);
})
},
this.$socket.emit("send", {
"theme": "XXXXX" + res.data.data.theme,
"mqttData": mqttData
})
如果不懂此,请参考我的另外两个博客
Node.js创建WEB服务(express)
Node.js连接MQTT服务器
创建 index.js
var net = require('net'); var express = require('express'); var app = express(); var server = net.createServer() 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) //socket部分 //监听uni-app页面的连接 io.on('connection', function(socket) { RealTimeUpdateSocket.RealTimeUpdateSocket[socket.id] = socket //新加入一个连接 socket.on('setRoom', function(data) { console.log(socket.id) // console.log(socket.id); var name = data.roomId; // 储存上线的用户 hashName[name + ''] = socket.id console.log(hashName) }) //监听uni-app发送的信息 socket.on("send", function(data) { WebsocketMqtt.sendMqttMsg(data.theme, data.mqttData); }) //断开事件 socket.on('disconnect', function(data) { console.log('断开', data) RealTimeUpdateSocket.RealTimeUpdateSocket.splice(data.id, 1) console.log(RealTimeUpdateSocket.RealTimeUpdateSocket.length) // socket.emit('c_leave', '离开'); //socket.broadcast用于向整个网络广播(除自己之外) socket.broadcast.emit('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() }) //设置消费结束 app.get('/setOver', function(req, res) { console.log(555) }) http.listen(8083, function() { var host = http.address().address var port = http.address().port console.log("应用实例,访问地址为 https://%s:%s", host, port) }) //与网页的连接 结束
WebsocketMqtt.js
const mqtt = require('mqtt') //页面实时更新的连接,全局 var RealTimeUpdateSocket = require("./RealTimeUpdateSocket.js") var randomCount = Math.ceil(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 = mqtt.connect('ws://你的域名/mqtt', options); client.on('reconnect', (error) => { console.log('正在重连:', error) }) client.on('error', (error) => { console.log('连接失败:', error) }) client.on('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 || '发布成功') // }) } }) }) client.on('message', (topic, message) => { console.log('收到来自', topic, '的消息', message.toString()) var data = JSON.parse(message.toString()); // 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 || '发布成功') }) } module.exports = { client: client, sendMqttMsg: sendMqttMsg, }
RealTimeUpdateSocket.js
//页面实时更新的连接,全局
var RealTimeUpdateSocket = []
module.exports = {
RealTimeUpdateSocket
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。