修改:接收 websocket 连接和获取消息列表

This commit is contained in:
安浩浩 2024-05-29 00:00:36 +08:00
parent ba23309f14
commit 294fb80b05
4 changed files with 83 additions and 92 deletions

View File

@ -1,7 +1,12 @@
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { shallowRef, defineAsyncComponent, DefineComponent } from 'vue'
import { webSocketStore } from '@/store/modules/webSocketStore'
import { getAccessToken } from '@/utils/auth'
import { useWebSocket } from '@vueuse/core'
import { imMessageStore, ImMessageWebSocket } from '@/store/modules/imMessageStore'
// imMessageStore addMessage
const { addMessage } = imMessageStore()
//
const IMComponent = defineAsyncComponent(() => import('@/views/im/index.vue'))
@ -14,11 +19,61 @@ function openDialog() {
dialogVisible.value = true
currentComponent.value = IMComponent // IM
}
// WebSocket
const { status, data, initWebSocket } = webSocketStore()
/** 监听接收到的数据 */
const messageList = ref([] as { time: number; text: string }[]) //
// WebSocket
function initWebSocket() {
const server =
(import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') +
'?token=' +
getAccessToken()
const { data } = useWebSocket(server, {
autoReconnect: true,
heartbeat: true,
onMessage(ws, event) {
// ws open
if (ws.readyState !== WebSocket.OPEN) return
try {
// 1.
if (data.value === 'pong') {
console.log('websocket 收到心跳包')
return
}
console.log('websocket 收到消息', event.data)
// 2.1 type
const jsonMessage = JSON.parse(data.value)
const type = jsonMessage.type
const content = JSON.parse(jsonMessage.content)
if (!type) {
// message.error('' + data.value)
return
}
// 2.2 demo-message-receive
if (type === 'im-message-receive') {
const message: ImMessageWebSocket = {
id: content.id,
conversationType: content.conversationType,
senderId: content.senderId,
senderNickname: content.senderNickname,
senderAvatar: content.senderAvatar,
receiverId: content.receiverId,
contentType: content.contentType,
content: content.content,
sendTime: content.sendTime,
sequence: content.sequence
}
// pina imMessageStore
addMessage(message)
return
}
} catch (error) {
console.error(error)
}
}
})
console.log('websocket 初始化成功')
}
// ========== =========
onMounted(() => {

View File

@ -18,9 +18,18 @@ export const imMessageStore = defineStore({
state: () => ({
messages: [] as ImMessageWebSocket[]
}),
getters: {
getMessages(): ImMessageWebSocket[] {
return this.messages
}
},
actions: {
addMessage(message: ImMessageWebSocket) {
this.messages.push(message)
}
}
})
export function useImMessageStore() {
return imMessageStore()
}

View File

@ -1,81 +0,0 @@
import { defineStore } from 'pinia'
import { useWebSocket, WebSocketStatus } from '@vueuse/core'
import { getAccessToken } from '@/utils/auth'
import { imMessageStore, ImMessageWebSocket } from './imMessageStore'
// 从 imMessageStore 中导入 addMessage 方法
const { addMessage } = imMessageStore()
export const webSocketStore = defineStore({
id: 'websocket',
state: () => ({
data: ref(null) as any,
status: ref<WebSocketStatus> as any,
close: null as ((code?: number | undefined, reason?: string | undefined) => void) | null,
open: null as (() => void) | null,
send: null as
| ((data: string | ArrayBuffer | Blob, useBuffer?: boolean | undefined) => boolean)
| null,
pingInterval: null as NodeJS.Timeout | null
}),
actions: {
initWebSocket() {
const server =
(import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') +
'?token=' +
getAccessToken(),
{ data, status, close, open, send } = useWebSocket(server, {
autoReconnect: true,
heartbeat: true,
onMessage(ws, event) {
// ws 状态不是 open 时不处理
if (ws.readyState !== WebSocket.OPEN) return
try {
// 1. 收到心跳
if (data.value === 'pong') {
console.log('websocket 收到心跳包')
return
}
console.log('websocket 收到消息', event.data)
// 2.1 解析 type 消息类型
const jsonMessage = JSON.parse(data.value)
const type = jsonMessage.type
const content = JSON.parse(jsonMessage.content)
if (!type) {
// message.error('未知的消息类型:' + data.value)
return
}
// 2.2 消息类型demo-message-receive
if (type === 'im-message-receive') {
const message: ImMessageWebSocket = {
id: content.id,
conversationType: content.conversationType,
senderId: content.senderId,
senderNickname: content.senderNickname,
senderAvatar: content.senderAvatar,
receiverId: content.receiverId,
contentType: content.contentType,
content: content.content,
sendTime: content.sendTime,
sequence: content.sequence
}
// 保存到 pina imMessageStore
addMessage(message)
return
}
} catch (error) {
console.error(error)
}
}
})
this.status = status
this.data = data
this.send = send
this.close = close
this.open = open
console.log('websocket 初始化成功')
}
}
})

View File

@ -5,7 +5,7 @@ import { messageType } from '@/constant/im'
import MessageList from './components/messageList/index.vue'
import InputBox from './components/inputBox/index.vue'
import * as MessageApi from '@/api/im/message'
import { ImMessageRespVO } from '@/api/im/message'
import { imMessageStore } from '@/store/modules/imMessageStore'
const { query } = useRoute() //
@ -45,11 +45,17 @@ const groupDetail = computed(() => {
})
//
const pullParams = reactive({
sequence: 0,
size: 100
sequence: null, // null
size: 10
})
const messageData = ref([])
const getMessageData = async () => {
//
const imMessages = imMessageStore().getMessages
if (imMessages) {
console.log('imMessages:' + imMessages)
console.log('imMessages:' + imMessages.length)
}
messageData.value = await MessageApi.pullMessageList(pullParams)
}
console.log(messageData)
@ -63,10 +69,12 @@ const fechHistoryMessage = (loadType) => {
console.log(loadType)
console.log('加载更多')
loadingHistoryMsg.value = true
// messageData sequence
if (messageData.value.length) {
pullParams.sequence = messageData.value[0].sequence
}
getMessageData()
setTimeout(() => {
loadingHistoryMsg.value = false
}, 1000)
loadingHistoryMsg.value = false
}
//
const scrollMessageList = (direction) => {