web聊天室数据同步修改

This commit is contained in:
2025-12-24 15:02:23 +08:00
parent 1fd26dcf1a
commit 898da3a2c6
16 changed files with 691 additions and 53 deletions

View File

@@ -108,10 +108,11 @@
</template>
<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { ref, reactive, computed, nextTick, onMounted, onUnmounted, watch } from 'vue'
import WorkcaseCreator from '@/components/WorkcaseCreator/WorkcaseCreator.uvue'
import type { ChatRoomMessageVO, CustomerVO, ChatMemberVO, TbChatRoomMessageDTO } from '@/types/workcase'
import { workcaseChatAPI } from '@/api/workcase'
import { wsClient } from '@/utils/websocket'
// 响应式数据
const headerPaddingTop = ref<number>(44)
@@ -232,6 +233,24 @@ onMounted(() => {
loadChatRoom()
loadDefaultWorkers()
loadChatMembers()
initWebSocket()
})
// 组件卸载时断开WebSocket
onUnmounted(() => {
disconnectWebSocket()
})
// 监听roomId变化切换聊天室时重新订阅
watch(roomId, (newRoomId, oldRoomId) => {
if (oldRoomId && newRoomId !== oldRoomId) {
// 取消旧聊天室订阅
wsClient.unsubscribe(`/topic/chat/${oldRoomId}`)
}
if (newRoomId && wsClient.isConnected()) {
// 订阅新聊天室
wsClient.subscribe(`/topic/chat/${newRoomId}`, handleNewMessage)
}
})
// 加载聊天室
@@ -443,6 +462,73 @@ function startMeeting() {
function goBack() {
uni.navigateBack()
}
// ==================== WebSocket连接管理 ====================
// 初始化WebSocket连接
async function initWebSocket() {
try {
const token = uni.getStorageSync('token') || ''
if (!token) {
console.warn('[chatRoom] 未找到token跳过WebSocket连接')
return
}
// 构建WebSocket URL
const protocol = 'wss:' // 生产环境使用wss
const host = 'your-domain.com' // 需要替换为实际域名
const wsUrl = `${protocol}//${host}/api/urban-lifeline/workcase/ws/chat-sockjs?token=${encodeURIComponent(token)}`
console.log('[chatRoom] 开始连接WebSocket')
await wsClient.connect(wsUrl, token)
// 订阅当前聊天室消息频道
if (roomId.value) {
wsClient.subscribe(`/topic/chat/${roomId.value}`, handleNewMessage)
console.log('[chatRoom] WebSocket连接成功已订阅聊天室:', roomId.value)
}
} catch (error) {
console.error('[chatRoom] WebSocket连接失败:', error)
}
}
// 断开WebSocket连接
function disconnectWebSocket() {
try {
if (roomId.value) {
wsClient.unsubscribe(`/topic/chat/${roomId.value}`)
}
wsClient.disconnect()
console.log('[chatRoom] WebSocket已断开')
} catch (error) {
console.error('[chatRoom] 断开WebSocket失败:', error)
}
}
// 处理接收到的新消息
function handleNewMessage(message: ChatRoomMessageVO) {
console.log('[chatRoom] 收到新消息:', message)
// 避免重复添加自己发送的消息自己发送的消息已经通过sendMessage添加到列表
if (message.senderId === currentUserId.value) {
console.log('[chatRoom] 跳过自己发送的消息')
return
}
// 检查消息是否已存在(避免重复)
const exists = messages.some(m => m.messageId === message.messageId)
if (exists) {
console.log('[chatRoom] 消息已存在,跳过')
return
}
// 添加新消息到列表
messages.push(message)
nextTick(() => scrollToBottom())
// 可以添加消息提示音或震动
// uni.vibrateShort()
}
</script>
<style lang="scss" scoped>

View File

@@ -50,9 +50,10 @@
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ref, onMounted, onUnmounted } from 'vue'
import { workcaseChatAPI } from '@/api'
import type { ChatRoomVO, TbChatRoomDTO, PageRequest } from '@/types'
import type { ChatRoomVO, TbChatRoomDTO, PageRequest, ChatRoomMessageVO } from '@/types'
import { wsClient } from '@/utils/websocket'
// 导航栏
const navPaddingTop = ref<number>(0)
@@ -86,6 +87,12 @@ onMounted(() => {
// #endif
loadChatRooms()
initWebSocket()
})
// 组件卸载时断开WebSocket
onUnmounted(() => {
disconnectWebSocket()
})
// 加载聊天室列表
@@ -170,6 +177,63 @@ function enterRoom(room: ChatRoomVO) {
function goBack() {
uni.navigateBack()
}
// ==================== WebSocket连接管理 ====================
// 初始化WebSocket连接
async function initWebSocket() {
try {
const token = uni.getStorageSync('token') || ''
if (!token) {
console.warn('[chatRoomList] 未找到token跳过WebSocket连接')
return
}
// 构建WebSocket URL
const protocol = 'wss:' // 生产环境使用wss
const host = 'your-domain.com' // 需要替换为实际域名
const wsUrl = `${protocol}//${host}/api/urban-lifeline/workcase/ws/chat-sockjs?token=${encodeURIComponent(token)}`
console.log('[chatRoomList] 开始连接WebSocket')
await wsClient.connect(wsUrl, token)
// 订阅聊天室列表更新频道
wsClient.subscribe('/topic/chat/list-update', handleListUpdate)
console.log('[chatRoomList] WebSocket连接成功已订阅列表更新频道')
} catch (error) {
console.error('[chatRoomList] WebSocket连接失败:', error)
}
}
// 断开WebSocket连接
function disconnectWebSocket() {
try {
wsClient.disconnect()
console.log('[chatRoomList] WebSocket已断开')
} catch (error) {
console.error('[chatRoomList] 断开WebSocket失败:', error)
}
}
// 处理列表更新消息
function handleListUpdate(message: ChatRoomMessageVO) {
console.log('[chatRoomList] 收到列表更新消息:', message)
// 更新对应聊天室的lastMessage和lastMessageTime
const roomIndex = chatRooms.value.findIndex((r: ChatRoomVO) => r.roomId === message.roomId)
if (roomIndex !== -1) {
chatRooms.value[roomIndex] = {
...chatRooms.value[roomIndex],
lastMessage: message.content || '',
lastMessageTime: message.sendTime || ''
}
// 将更新的聊天室移到列表顶部
const updatedRoom = chatRooms.value[roomIndex]
chatRooms.value.splice(roomIndex, 1)
chatRooms.value.unshift(updatedRoom)
}
}
</script>
<style lang="scss" scoped>

View File

@@ -0,0 +1,339 @@
/**
* WebSocket工具类
* 支持STOMP协议和uni.connectSocket API
*/
interface StompFrame {
command: string
headers: Record<string, string>
body: string
}
interface SubscriptionCallback {
(message: any): void
}
export class WebSocketClient {
private socketTask: any | null = null
private connected: boolean = false
private subscriptions: Map<string, SubscriptionCallback> = new Map()
private messageQueue: string[] = []
private heartbeatTimer: number | null = null
private reconnectTimer: number | null = null
private reconnectAttempts: number = 0
private maxReconnectAttempts: number = 5
private url: string = ''
private token: string = ''
constructor() {}
/**
* 连接WebSocket
*/
connect(url: string, token: string): Promise<void> {
return new Promise((resolve, reject) => {
this.url = url
this.token = token
console.log('[WebSocket] 开始连接:', url)
this.socketTask = uni.connectSocket({
url: url,
success: () => {
console.log('[WebSocket] 连接请求已发送')
},
fail: (err: any) => {
console.error('[WebSocket] 连接失败:', err)
reject(err)
}
})
if (!this.socketTask) {
reject(new Error('创建WebSocket失败'))
return
}
// 监听打开
this.socketTask.onOpen(() => {
console.log('[WebSocket] 连接已建立')
this.connected = true
this.reconnectAttempts = 0
// 发送STOMP CONNECT帧
this.sendStompFrame({
command: 'CONNECT',
headers: {
'accept-version': '1.2',
'heart-beat': '10000,10000',
'Authorization': `Bearer ${this.token}`
},
body: ''
})
// 启动心跳
this.startHeartbeat()
resolve()
})
// 监听消息
this.socketTask.onMessage((res: any) => {
const data = res.data as string
this.handleMessage(data)
})
// 监听关闭
this.socketTask.onClose(() => {
console.log('[WebSocket] 连接已关闭')
this.connected = false
this.stopHeartbeat()
this.handleReconnect()
})
// 监听错误
this.socketTask.onError((err: any) => {
console.error('[WebSocket] 连接错误:', err)
this.connected = false
})
})
}
/**
* 断开连接
*/
disconnect() {
console.log('[WebSocket] 主动断开连接')
this.stopHeartbeat()
this.clearReconnectTimer()
this.reconnectAttempts = this.maxReconnectAttempts // 阻止自动重连
if (this.socketTask) {
this.socketTask.close({
success: () => {
console.log('[WebSocket] 断开成功')
}
})
this.socketTask = null
}
this.connected = false
this.subscriptions.clear()
this.messageQueue = []
}
/**
* 订阅主题
*/
subscribe(destination: string, callback: SubscriptionCallback): string {
const id = `sub-${Date.now()}-${Math.random()}`
console.log('[WebSocket] 订阅主题:', destination, 'id:', id)
this.subscriptions.set(destination, callback)
if (this.connected) {
this.sendStompFrame({
command: 'SUBSCRIBE',
headers: {
'id': id,
'destination': destination
},
body: ''
})
} else {
console.warn('[WebSocket] 未连接,订阅已加入队列')
}
return id
}
/**
* 取消订阅
*/
unsubscribe(destination: string) {
console.log('[WebSocket] 取消订阅:', destination)
this.subscriptions.delete(destination)
if (this.connected) {
this.sendStompFrame({
command: 'UNSUBSCRIBE',
headers: {
'destination': destination
},
body: ''
})
}
}
/**
* 发送STOMP帧
*/
private sendStompFrame(frame: StompFrame) {
let message = frame.command + '\n'
for (const key in frame.headers) {
message += `${key}:${frame.headers[key]}\n`
}
message += '\n' + frame.body + '\x00'
if (this.connected && this.socketTask) {
this.socketTask.send({
data: message,
success: () => {
console.log('[WebSocket] 发送成功:', frame.command)
},
fail: (err) => {
console.error('[WebSocket] 发送失败:', err)
}
})
} else {
console.warn('[WebSocket] 未连接,消息已加入队列')
this.messageQueue.push(message)
}
}
/**
* 处理接收到的消息
*/
private handleMessage(data: string) {
console.log('[WebSocket] 收到消息:', data.substring(0, 200))
const frame = this.parseStompFrame(data)
if (frame.command === 'CONNECTED') {
console.log('[WebSocket] STOMP连接成功')
// 处理队列中的订阅
this.subscriptions.forEach((callback, destination) => {
const id = `sub-${Date.now()}-${Math.random()}`
this.sendStompFrame({
command: 'SUBSCRIBE',
headers: {
'id': id,
'destination': destination
},
body: ''
})
})
// 发送队列中的消息
while (this.messageQueue.length > 0) {
const msg = this.messageQueue.shift()
if (msg && this.socketTask) {
this.socketTask.send({ data: msg })
}
}
} else if (frame.command === 'MESSAGE') {
const destination = frame.headers['destination']
const callback = this.subscriptions.get(destination)
if (callback) {
try {
const message = JSON.parse(frame.body)
callback(message)
} catch (e) {
console.error('[WebSocket] 解析消息失败:', e)
}
}
} else if (frame.command === 'ERROR') {
console.error('[WebSocket] 服务器错误:', frame.body)
}
}
/**
* 解析STOMP帧
*/
private parseStompFrame(data: string): StompFrame {
const lines = data.split('\n')
const command = lines[0]
const headers: Record<string, string> = {}
let bodyStart = 0
for (let i = 1; i < lines.length; i++) {
const line = lines[i]
if (line === '') {
bodyStart = i + 1
break
}
const colonIndex = line.indexOf(':')
if (colonIndex > 0) {
const key = line.substring(0, colonIndex)
const value = line.substring(colonIndex + 1)
headers[key] = value
}
}
const body = lines.slice(bodyStart).join('\n').replace(/\x00$/, '')
return { command, headers, body }
}
/**
* 启动心跳
*/
private startHeartbeat() {
this.stopHeartbeat()
this.heartbeatTimer = setInterval(() => {
if (this.connected && this.socketTask) {
this.socketTask.send({
data: '\n',
fail: () => {
console.warn('[WebSocket] 心跳发送失败')
}
})
}
}, 10000) as unknown as number
}
/**
* 停止心跳
*/
private stopHeartbeat() {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer)
this.heartbeatTimer = null
}
}
/**
* 处理重连
*/
private handleReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.log('[WebSocket] 达到最大重连次数,停止重连')
return
}
this.clearReconnectTimer()
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000)
console.log(`[WebSocket] ${delay}ms后尝试重连 (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`)
this.reconnectTimer = setTimeout(() => {
this.reconnectAttempts++
this.connect(this.url, this.token).catch((err: any) => {
console.error('[WebSocket] 重连失败:', err)
})
}, delay) as unknown as number
}
/**
* 清除重连定时器
*/
private clearReconnectTimer() {
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
}
}
/**
* 检查连接状态
*/
isConnected(): boolean {
return this.connected
}
}
// 导出单例
export const wsClient = new WebSocketClient()