修复MQTT连接与消息收发逻辑- 修复发送按钮禁用状态判断条件
- 添加selfClientId存储与使用 - 完善MQTT消息订阅与接收处理-优化消息发送逻辑与数据格式 - 调整MQTT配置获取与clientId绑定 - 清理冗余代码与注释 - 修复消息列表滚动定位问题 - 完善错误处理与连接状态提示
This commit is contained in:
parent
42386a201f
commit
3b31071e13
@ -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 {
|
||||||
// // 直接使用已创建的MQTT实例的clientId
|
|
||||||
// if (this.mqttUtils && this.mqttUtils.options.clientId) {
|
|
||||||
// this.mqttConfig.clientId = this.mqttUtils.options.clientId;
|
|
||||||
// return Promise.resolve();
|
|
||||||
// }
|
|
||||||
|
|
||||||
// 如果没有已创建的实例或clientId,则通过API获取
|
// 如果没有已创建的实例或clientId,则通过API获取
|
||||||
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
|
||||||
// 如果MQTT实例已创建,更新clientId
|
|
||||||
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, // 聊天列表的ID,这里暂时固定为1
|
bind_id: this.mqttConfig.bind_id, // 聊天列表的ID,这里暂时固定为1
|
||||||
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)
|
||||||
// 可以在这里添加消息发送失败的处理逻辑
|
// 可以在这里添加消息发送失败的处理逻辑
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user