no message

This commit is contained in:
小陌 2023-09-19 16:41:24 +08:00
parent c750242da5
commit f72d4b644d
2 changed files with 23 additions and 5 deletions

View File

@ -90,14 +90,15 @@ router.beforeEach(async (to, from, next) => {
} }
isGetRouter = true; 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({ store.state.socket.send(JSON.stringify({
type: 'bind', type: 'bind',
data: { data: {
token: token, token: token,
uid: response.data.user.uid uid: response.data.user.uid || 0
} }
})) }));
console.log('WebSocket router 用户绑定成功');
} }
} }
}).catch((error) => { }).catch((error) => {

View File

@ -1,8 +1,12 @@
import config from '@/config'; import config from '@/config';
import { ref } from 'vue'; import {
ref
} from 'vue';
import tool from '@/utils/tool';
let socket; let socket;
let reconnectAttempts = 1; let reconnectAttempts = 1;
const maxReconnectAttempts = 5; const maxReconnectAttempts = 5;
const socketState = ref(socket);
export function createWebSocket() { export function createWebSocket() {
let socketurl = config.WEBSOCKET || null; let socketurl = config.WEBSOCKET || null;
if (socketurl) { if (socketurl) {
@ -10,6 +14,20 @@ export function createWebSocket() {
socket = new WebSocket(socketurl); socket = new WebSocket(socketurl);
socket.onopen = function() { socket.onopen = function() {
console.log('WebSocket连接成功'); 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 reconnectAttempts = 0; // reset reconnect attempts
} }
socket.onerror = function() { socket.onerror = function() {
@ -40,7 +58,6 @@ function reconnect() {
console.log('WebSocket重连失败'); console.log('WebSocket重连失败');
} }
} }
const socketState = ref(socket);
createWebSocket(); createWebSocket();
export default { export default {
state: socketState state: socketState