diff --git a/src/router/index.js b/src/router/index.js index f7c5a2e..a21c8d1 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -90,14 +90,15 @@ router.beforeEach(async (to, from, next) => { } isGetRouter = true; // 发送绑定 - if (store.state.socket && store.state.socket.readyState === WebSocket.OPEN) { + if (store.state.socket && store.state.socket.readyState === WebSocket.OPEN && tool.store.get('socketbinduser', '') !== token) { store.state.socket.send(JSON.stringify({ type: 'bind', data: { token: token, - uid: response.data.user.uid + uid: response.data.user.uid || 0 } - })) + })); + console.log('WebSocket router 用户绑定成功'); } } }).catch((error) => { diff --git a/src/store/modules/socket.js b/src/store/modules/socket.js index de56cf8..61b24b1 100644 --- a/src/store/modules/socket.js +++ b/src/store/modules/socket.js @@ -1,8 +1,12 @@ import config from '@/config'; -import { ref } from 'vue'; +import { + ref +} from 'vue'; +import tool from '@/utils/tool'; let socket; let reconnectAttempts = 1; const maxReconnectAttempts = 5; +const socketState = ref(socket); export function createWebSocket() { let socketurl = config.WEBSOCKET || null; if (socketurl) { @@ -10,6 +14,20 @@ export function createWebSocket() { socket = new WebSocket(socketurl); socket.onopen = function() { console.log('WebSocket连接成功'); + var user = tool.data.get('user') || {}; + var token = tool.cookie.get(config.SESSIONNAME); + if (user && token) { + // 绑定用户 + socket.send(JSON.stringify({ + type: 'bind', + data: { + token: token, + uid: user.uid || 0 + } + })) + tool.store.set('socketbinduser', token); + console.log('WebSocket 用户绑定成功'); + } reconnectAttempts = 0; // reset reconnect attempts } socket.onerror = function() { @@ -40,7 +58,6 @@ function reconnect() { console.log('WebSocket重连失败'); } } -const socketState = ref(socket); createWebSocket(); export default { state: socketState