// mqtt与服务端连接
connect: function() {
let hosts = 'wx://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;
let that = this;
if (client == null || client.connected == false) {
// console.log(hosts, this.options);
client = mqtt.connect(hosts, this.options);
client.on("connect", () => {
console.log('连接成功')
client.subscribe(that.onTopic, {
qos: 0
}, function(res) {
if (!res) {
console.log(res, '订阅成功');
that.onMessage();
}
})
});
} else {
console.log('mqtt连接失败');
}
client.on('reconnect', function(error) {
console.log('正在重连......')
}).on('error', function(error) {
console.log('连接失败...', error)
that.connect();
}).on('end', function() {
console.log('连接断开')
})
},

- 发布:2021-05-05 09:34
- 更新:2021-05-06 11:01
- 阅读:865
产品分类: uniapp/App
PC开发环境操作系统: Windows
PC开发环境操作系统版本号: 10
HBuilderX类型: 正式
HBuilderX版本号: 3.1.12
手机系统: Android
手机系统版本号: Android 10
手机厂商: 华为
手机机型: 华为mate30Pro 5G
页面类型: nvue
打包方式: 云端
项目创建方式: HBuilderX
示例代码:
操作步骤:
import mqtt from '../../utils/mqtt.js';
var client;
export default {
onShow: function() {
this.connect();
},
methods: {
// mqtt与服务端连接
connect: function() {
let hosts = 'wx://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;
let that = this;
if (client == null || client.connected == false) {
// console.log(hosts, this.options);
client = mqtt.connect(hosts, this.options);
client.on("connect", () => {
console.log('连接成功')
client.subscribe(that.onTopic, {
qos: 0
}, function(res) {
if (!res) {
console.log(res, '订阅成功');
that.onMessage();
}
})
});
} else {
console.log('mqtt连接失败');
}
client.on('reconnect', function(error) {
console.log('正在重连......')
}).on('error', function(error) {
console.log('连接失败...', error)
that.connect();
}).on('end', function() {
console.log('连接断开')
})
},
}
}
import mqtt from '../../utils/mqtt.js';
var client;
export default {
onShow: function() {
this.connect();
},
methods: {
// mqtt与服务端连接
connect: function() {
let hosts = 'wx://' + this.serve.host + ':' + this.serve.wsport + this.serve.path;
let that = this;
if (client == null || client.connected == false) {
// console.log(hosts, this.options);
client = mqtt.connect(hosts, this.options);
client.on("connect", () => {
console.log('连接成功')
client.subscribe(that.onTopic, {
qos: 0
}, function(res) {
if (!res) {
console.log(res, '订阅成功');
that.onMessage();
}
})
});
} else {
console.log('mqtt连接失败');
}
client.on('reconnect', function(error) {
console.log('正在重连......')
}).on('error', function(error) {
console.log('连接失败...', error)
that.connect();
}).on('end', function() {
console.log('连接断开')
})
},
}
}
预期结果:
正常发消息连接,并且不白屏,一切显示正常。
正常发消息连接,并且不白屏,一切显示正常。
实际结果:
页面白屏并报错。
页面白屏并报错。
2***@qq.com (作者)
又报这个错误了【reportJSException >>>> exception function:createInstanceContext, exception:white screen cause create instanceContext failed,check js stack ->Uncaught ReferenceError: require is not defined】,我用npm引入的,然后在页面中是这样的【var mqtt = require('mqtt');】,就报上面这个错误了,然后页面白屏,有问题还报错了。
2021-05-12 13:44