add ws消息推送

This commit is contained in:
2025-09-28 17:28:34 +08:00
parent 3642473b28
commit 4197e4185e
3 changed files with 474 additions and 0 deletions

View File

@@ -40,6 +40,9 @@
export default {
data() {
return {
reconnectTimer: null,
websocket: null,
serverUrl: this.$store.getters.baseUrl,
userName: '',
// menuList: [
// {title: '库位管理', path: 'RF03', sonTree: [{title: '人工取货', path: '/pages/ftdl/man-get-goods'}, {title: '人工放货', path: '/pages/ftdl/man-load-goods'}, {title: '库存锁定/解锁', path: '/pages/ftdl/kc-manage'}]},
@@ -71,7 +74,88 @@
// }
// },
mounted() {
this.initWebSocket()
},
methods: {
initWebSocket() {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
const wsHost = this.serverUrl.replace(/^https?:\/\//, '')
const sid = 'sid' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
const wsUrl = `ws://${wsHost}/webSocket/${sid}`
console.log(wsUrl, 666)
this.closeWebSocket()
// 使用 uni.connectSocket 创建连接
this.socketTask = uni.connectSocket({
url: wsUrl,
success: () => {
console.log('WebSocket 连接创建成功')
},
fail: (err) => {
console.error('WebSocket 连接创建失败:', err)
this.reconnectWebSocket()
}
})
// 监听 WebSocket 事件
this.socketTask.onOpen(() => {
console.log('WebSocket 连接已打开')
})
this.socketTask.onMessage((event) => {
try {
const res = JSON.parse(event.data)
this.handleWebSocketMessage(res)
} catch (error) {
console.error('WebSocket消息解析失败:', error)
}
})
this.socketTask.onError((error) => {
console.error('WebSocket 错误:', error)
uni.showToast({
title: '连接错误',
icon: 'none'
})
})
this.socketTask.onClose(() => {
console.log('WebSocket 连接已关闭')
this.reconnectWebSocket()
})
},
handleWebSocketMessage(res) {
console.log(res, 'res')
console.log(res.msg.data, 'res.msg.data')
uni.showToast({
title: res.msg.data,
icon: 'none'
})
},
closeWebSocket() {
if (this.socketTask) {
this.socketTask.close({
success: () => {
console.log('WebSocket 已关闭')
},
fail: (err) => {
console.error('关闭 WebSocket 失败:', err)
}
})
this.socketTask = null
}
},
reconnectWebSocket() {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
this.reconnectTimer = setTimeout(() => {
this.initWebSocket()
}, 5000) // 5秒后重连
},
toPage1 (e) {
if (e.sonTree.length > 0) {
this.show = true