修改mqtt,根据http 或者http动态修改ws wss访问地址

This commit is contained in:
fengerli
2025-09-19 10:33:42 +08:00
parent 9be161d8aa
commit b83df1cfbf
2 changed files with 19 additions and 16 deletions

View File

@ -5,8 +5,8 @@ const config = {
BASE_URL: 'http://192.168.2.34:8000',
API_PREFIX: '',
// MQTT 配置
MQTT_HOST: '47.120.79.150',
MQTT_PORT: 8083,
MQTT_HOST: 'www.cnxhyc.com',
MQTT_PORT: 9083,
MQTT_USERNAME: 'admin',
MQTT_PASSWORD: '#YtvpSfCNG'
},
@ -15,8 +15,8 @@ const config = {
BASE_URL: 'https://fuyuanshen.com/backend',
API_PREFIX: '',
// MQTT 配置
MQTT_HOST: '47.120.79.150',
MQTT_PORT: 8083,
MQTT_HOST: 'www.cnxhyc.com',
MQTT_PORT: 9084,
MQTT_USERNAME: 'admin',
MQTT_PASSWORD: '#YtvpSfCNG'
}

View File

@ -117,19 +117,20 @@
*/
import Paho from 'paho-mqtt';
import allConfigs from '../config/index.js';
// 根据环境选择正确的配置
const env = 'production'; //production //开发of线上 改这里就行
const config = allConfigs[env];
const env = 'production'; //production development
const envConfig = allConfigs[env];
const mqttProtocol = env === 'production' ? 'wss' : 'ws';
const useSSL = env === 'production';
class MqttClient {
constructor() {
this.client = null;
this.options = {
host: config.MQTT_HOST,
port: config.MQTT_PORT,
host: envConfig.MQTT_HOST,
port: envConfig.MQTT_PORT,
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: config.MQTT_USERNAME,
password: config.MQTT_PASSWORD,
username: envConfig.MQTT_USERNAME,
password: envConfig.MQTT_PASSWORD,
};
this.onConnectCallback = null;
this.messageCallbacks = new Map();
@ -189,16 +190,18 @@ class MqttClient {
this.manualDisconnect = false;
this.onConnectCallback = onConnectCallback;
console.log(`正在连接MQTT: ${this.options.host}:${this.options.port}/mqtt`);
console.log(`环境识别http https${env}`, {
connectUrl: `${mqttProtocol}://${this.options.host}:${this.options.port}/mqtt`,
useSSL: useSSL,
clientId: this.options.clientId
});
try {
const connectOptions = {
timeout: 10, // 增加连接超时时间,应对网络波动
keepAliveInterval: 30, // 明确设置心跳间隔为30秒
userName: this.options.username,
password: this.options.password,
useSSL: false,
useSSL: useSSL, //http ws https wss开启
cleanSession: true,
onSuccess: () => {
console.log('MQTT连接成功');