修复MQTT连接与消息收发逻辑- 修复发送按钮禁用状态判断条件

- 添加selfClientId存储与使用
- 完善MQTT消息订阅与接收处理-优化消息发送逻辑与数据格式
- 调整MQTT配置获取与clientId绑定
- 清理冗余代码与注释
- 修复消息列表滚动定位问题
- 完善错误处理与连接状态提示
This commit is contained in:
maguodong 2025-09-24 15:37:34 +08:00
parent 42386a201f
commit 3b31071e13

View File

@ -45,7 +45,7 @@
<view class="input-container"> <view class="input-container">
<textarea v-model="inputMessage" :adjust-position="true" class="message-input" placeholder="请输入消息..." <textarea v-model="inputMessage" :adjust-position="true" class="message-input" placeholder="请输入消息..."
@confirm="sendMessage" @input="handleInput"></textarea> @confirm="sendMessage" @input="handleInput"></textarea>
<button :disabled="!canSend || !client || !client.isConnected" class="send-btn" @tap="sendMessage"> <button :disabled="!canSend || !client || !isConnected" class="send-btn" @tap="sendMessage">
发送 发送
</button> </button>
</view> </view>
@ -88,8 +88,10 @@ export default {
isLoadingHistory: false, isLoadingHistory: false,
// //
keepaliveTimer: null, keepaliveTimer: null,
selfClientId: uni.getStorageSync('openId'),
// MQTT // MQTT
client: null, client: null,
mqttConfig: {},
// //
reconnectFailedTimer: null reconnectFailedTimer: null
} }
@ -103,46 +105,46 @@ export default {
this.chatTarget = JSON.parse(options.item) this.chatTarget = JSON.parse(options.item)
this.chatTarget.title = `客服${ this.chatTarget.employee_name }` this.chatTarget.title = `客服${ this.chatTarget.employee_name }`
} }
// MQTT
// this.mqttUtils = new MqttUtils({
// username: 'dev01',
// password: '211561',
// clientId: 'mqtt_8812321421_' + Math.random().toString(16).substr(2, 8),
// protocolVersion: 3,
// connectTimeout: 30 * 1000,
// reconnectPeriod: 5000,
// keepalive: 60,
// clean: true,
// //
// maxReconnectAttempts: 15,
// reconnectExponentialBackoff: true
// });
// this.mqttUtils.connect()
// MQTT // MQTT
this.initChat() this.initChat()
this.getMqttConfig()
}, },
onShow(){ onShow(){
// MQTT
// if (this.mqttUtils && !this.mqttUtils.getIsConnected()) {
// this.connectingStatus = '...';
// }
}, },
methods: { methods: {
async connect(){ async connect(){
const options = { const options = {
clientId: 'mqtt_888888888' clientId: this.selfClientId
} }
this.client = MqttUtils.connect(options) this.client = MqttUtils.connect(options)
this.isConnected = !!this.client this.isConnected = !!this.client
await this.subscribe()
this.client.on('message', (topic, message) => {
let de = new TextDecoder('utf-8')
let msg = de.decode(message)
let jsMsg = JSON.parse(msg)
console.log('收到消息', topic, msg)
if (jsMsg.send_client === this.selfClientId || jsMsg.receive_client === this.selfClientId) {
console.log('接收或发送人是我')
if (jsMsg.send_client === this.mqttConfig.clientId || jsMsg.receive_client === this.mqttConfig.clientId) {
console.log('接收或发送人是我的聊天对象')
this.messages.push({
content: jsMsg.content,
time: Date.now(),
isSelf: jsMsg.send_client === this.selfClientId,
isLoading: false
})
console.log('收到我的消息', this.messages)
this.scrollToView = 'msg-' + (this.messages.length - 1)
}
}
})
}, },
async subscribe(){ async subscribe(){
if (this.isConnected && this.client) { if (this.isConnected && this.client) {
this.client.subscribe('contact/message/receive_msg', { qos: 0 }, function(err){ this.client.subscribe('contact/message/receive_msg', { qos: 0 }, function(err){
if (!err) { if (!err) {
console.log('订阅成功') console.log('订阅成功', 'contact/message/receive_msg', { qos: 0 })
this.client.publish({ 'contact/message/send_msg': 0 }, 'hello mqtt')
} else { } else {
console.log('订阅失败:', err) console.log('订阅失败:', err)
this.connectingStatus = '订阅失败,请重试' this.connectingStatus = '订阅失败,请重试'
@ -157,123 +159,7 @@ export default {
try { try {
// //
this.connectingStatus = '连接中...' this.connectingStatus = '连接中...'
await this.connect() await this.connect()
// // MQTT
// await this.getMqttConfig();
// // MQTT
// this.mqttUtils.connect();
// //
// this.mqttUtils.on('connect', (connack) => {
// console.log('MQTT:', connack);
// this.isConnected = true;
// this.connectingStatus = '';
// //
// this.mqttUtils.subscribe('contact/message/receive_msg', (err) => {
// if (err) {
// console.error(':', err);
// this.connectingStatus = '';
// } else {
// console.log(': contact/message/receive_msg');
// //
// this.loadHistoryMessages();
// //
// this.startKeepalive();
// }
// });
// });
// this.mqttUtils.on('error', (error) => {
// console.log('MQTT:', error);
// console.error(':', error.code);
// console.error(':', error.message);
// this.isConnected = false;
// this.connectingStatus = '';
// });
// this.mqttUtils.on('disconnect', () => {
// console.log('MQTT');
// })
// this.mqttUtils.on('message', (topic, message) => {
// console.log(':', topic, message.toString());
// try {
// //
// let msgData;
// if (typeof message === 'string') {
// try {
// msgData = JSON.parse(message);
// } catch (e) {
// console.error('', e);
// return;
// }
// } else {
// msgData = JSON.parse(message.toString());
// }
// //
// if (msgData.receive_client === this.mqttConfig.clientId &&
// msgData.send_client === this.chatTarget.openId) {
// //
// this.messages.push({
// id: `msg_${Date.now()}_${Math.random()}`,
// content: msgData.content,
// isSelf: false,
// time: Date.now(),
// isLoading: false
// });
// //
// this.scrollToBottom();
// }
// } catch (error) {
// console.error('', error);
// }
// });
// this.mqttUtils.on('reconnect', (attempts, delay) => {
// console.log('MQTT...', attempts, delay);
// this.connectingStatus = `(${attempts})...`;
// });
// this.mqttUtils.on('close', () => {
// console.log('MQTT');
// this.isConnected = false;
// this.connectingStatus = '';
// this.stopKeepalive();
// });
// this.mqttUtils.on('offline', () => {
// console.log('MQTT线');
// this.isConnected = false;
// this.connectingStatus = '线';
// this.stopKeepalive();
// });
// this.mqttUtils.on('end', () => {
// console.log('MQTT');
// this.isConnected = false;
// this.connectingStatus = '';
// this.stopKeepalive();
// });
// //
// this.mqttUtils.on('reconnectFailed', () => {
// console.error('MQTT');
// this.connectingStatus = '';
// // 5
// this.reconnectFailedTimer = setTimeout(() => {
// console.log('');
// this.initChat();
// }, 5000);
// });
} catch (error) { } catch (error) {
console.error('初始化聊天失败', error) console.error('初始化聊天失败', error)
this.connectingStatus = '连接失败,请重试' this.connectingStatus = '连接失败,请重试'
@ -289,29 +175,19 @@ export default {
async getMqttConfig(){ async getMqttConfig(){
console.log('🚀 ~ getMqttConfig ~ getMqttConfig:', 11111) console.log('🚀 ~ getMqttConfig ~ getMqttConfig:', 11111)
try { try {
// // 使MQTTclientId
// if (this.mqttUtils && this.mqttUtils.options.clientId) {
// this.mqttConfig.clientId = this.mqttUtils.options.clientId;
// return Promise.resolve();
// }
// clientIdAPI // clientIdAPI
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const params = { const params = {
worker_id: this.chatTarget.id || '', worker_id: this.chatTarget.id || '',
open_id: uni.getStorageSync('openId') || '' open_id: this.selfClientId || ''
} }
request(apiArr.csGetToClientId, 'POST', params).then((res) => { request(apiArr.csGetToClientId, 'POST', params).then((res) => {
console.log('聊天列表:', res)
// //
if (res && res.client_bind && res.client_bind.client_id_one && res.client_bind.client_id_two) { if (res && res.client_bind && res.client_bind.client_id_one && res.client_bind.client_id_two) {
this.mqttConfig.clientId = res.client_bind.client_id_one // open_id this.mqttConfig.clientId = res.client_bind.client_id_one // open_id
this.chatTarget.openId = res.client_bind.client_id_two // open_id this.chatTarget.openId = res.client_bind.client_id_two // open_id
this.mqttConfig.bind_id = res.client_bind.id
// MQTTclientId
if (this.mqttUtils) {
this.mqttUtils.options.clientId = this.mqttConfig.clientId
}
resolve() resolve()
} else { } else {
console.error('MQTT配置响应格式不正确:', res) console.error('MQTT配置响应格式不正确:', res)
@ -371,44 +247,26 @@ export default {
// //
sendMessage(){ sendMessage(){
const content = this.inputMessage.trim() const content = this.inputMessage.trim()
console.log('发送消息', content)
if (!content || !this.client || !this.isConnected) return if (!content || !this.client || !this.isConnected) return
//
const message = {
id: `msg_${ Date.now() }_${ Math.random() }`,
content: content,
isSelf: true,
time: Date.now(),
isLoading: true
}
//
// this.messages.push(message);
// //
this.scrollToBottom() this.scrollToBottom()
console.log('需要发送的对象', this.mqttConfig)
// //
const msgData = { const msgData = {
bind_id: 1, // ID1 bind_id: this.mqttConfig.bind_id, // ID1
send_client: this.mqttConfig.clientId, // open_id send_client: this.mqttConfig.clientId, // open_id
receive_client: this.chatTarget.openId, // open_id receive_client: this.chatTarget.openId, // open_id
type: 1, // 1 type: 1, // 1
content: content, // content: content, //
receive_read_status: 2 // receive_read_status: 2 //
} }
console.log('发送消息', msgData)
this.client.publish( this.client.publish(
'contact/message/send_msg', // 使 'contact/message/send_msg', // 使
JSON.stringify(msgData), JSON.stringify(msgData),
{ Qos: 0 }, { Qos: 0 },
(err) => { (err) => {
//
const index = this.messages.findIndex(m => m.id === message.id)
if (index !== -1) {
this.$set(this.messages[index], 'isLoading', false)
}
if (err) { if (err) {
console.error('发送消息失败', err) console.error('发送消息失败', err)
// //