no message
This commit is contained in:
parent
a15732a789
commit
50fa3fe16e
@ -1,19 +1,20 @@
|
||||
import config from '@/config';
|
||||
import {
|
||||
ref
|
||||
} from 'vue';
|
||||
import { ref } from 'vue';
|
||||
import tool from '@/utils/tool';
|
||||
|
||||
let socket;
|
||||
let reconnectAttempts = 1;
|
||||
let intervalId; // 用于保存心跳请求的定时器id
|
||||
const maxReconnectAttempts = 5;
|
||||
const heartbeatInterval = 50000;
|
||||
const socketState = ref(socket);
|
||||
|
||||
export function createWebSocket() {
|
||||
let socketurl = config.WEBSOCKET || null;
|
||||
if (socketurl) {
|
||||
try {
|
||||
socket = new WebSocket(socketurl);
|
||||
socket.onopen = function() {
|
||||
socket.onopen = function () {
|
||||
console.log('WebSocket连接成功');
|
||||
var user = tool.data.get('user') || {};
|
||||
var token = tool.cookie.get(config.SESSIONNAME);
|
||||
@ -32,18 +33,21 @@ export function createWebSocket() {
|
||||
}
|
||||
reconnectAttempts = 0; // reset reconnect attempts
|
||||
|
||||
// 清除之前的定时器
|
||||
clearInterval(intervalId);
|
||||
|
||||
// 定时发送心跳请求
|
||||
setInterval(function() {
|
||||
intervalId = setInterval(function () {
|
||||
socket.send(JSON.stringify({
|
||||
type: 'ping'
|
||||
}));
|
||||
}, heartbeatInterval);
|
||||
}
|
||||
socket.onerror = function() {
|
||||
socket.onerror = function () {
|
||||
console.log('WebSocket连接发生错误');
|
||||
reconnect();
|
||||
}
|
||||
socket.onclose = function() {
|
||||
socket.onclose = function () {
|
||||
console.log('WebSocket连接关闭');
|
||||
reconnect();
|
||||
}
|
||||
@ -58,7 +62,7 @@ export function createWebSocket() {
|
||||
|
||||
function reconnect() {
|
||||
if (maxReconnectAttempts > reconnectAttempts) {
|
||||
setTimeout(function() {
|
||||
setTimeout(function () {
|
||||
createWebSocket();
|
||||
console.log('WebSocket进行重连(' + reconnectAttempts);
|
||||
reconnectAttempts++;
|
||||
@ -67,7 +71,9 @@ function reconnect() {
|
||||
console.log('WebSocket重连失败');
|
||||
}
|
||||
}
|
||||
|
||||
createWebSocket();
|
||||
|
||||
export default {
|
||||
state: socketState
|
||||
}
|
Loading…
Reference in New Issue
Block a user