perf: 上传文件后有时没有自动刷新的问题

This commit is contained in:
jmal 2024-03-09 13:56:14 +08:00
parent 0048dd71a6
commit a92330f7d1
11 changed files with 70 additions and 724 deletions

View File

@ -55,8 +55,7 @@
"vue-runtime-helpers": "^1.1.2",
"vue-simple-uploader": "0.7.6",
"vuedraggable": "^2.23.2",
"vuex": "^3.1.0",
"websocket": "^1.0.34"
"vuex": "^3.1.0"
},
"devDependencies": {
"@babel/core": "7.0.0",

View File

@ -1415,8 +1415,8 @@ export default {
}
},
onmessage(msg) {
let fileDoc = JSON.parse(msg.body);
const url = msg.headers.url;
let fileDoc = msg.body
const url = msg.url;
let index = this.fileList.findIndex(file => file.id === fileDoc.id);
if ("updateFile" === url) {
if (index > -1) {

View File

@ -112,7 +112,7 @@ export default {
},
methods: {
onmessage(msg) {
const takeUpSpace = msg.headers.space
const takeUpSpace = msg.space
if (takeUpSpace) {
this.takeUpSpace = takeUpSpace
const space = takeUpSpace/1024/1024/1024

View File

@ -21,9 +21,7 @@ import ResizeMixin from './mixin/ResizeHandler'
import { getToken } from '@/utils/auth'
import AudioPreview from "@/components/preview/AudioPreview";
import globalUploader from '@/components/SimpleUploader/globalUploader.vue'
import {toConnection} from "@/websocket/sockJS";
import ws from '@/websocket/websocket_config';
import { connectToSSE } from '@/sse/SSEClient'
export default {
name: 'Layout',
@ -63,10 +61,8 @@ export default {
window.pc = !/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
if(getToken()){
this.isShow = window.pc;
//与服务器建立websocket连接
if(!ws.isConnected){
toConnection(this.$store.state.user.name,this.$store.state.user.token);
}
// 与服务器建立sse连接
connectToSSE(this.$store.state.user.name)
if(this.$route.path.startsWith('/setting')){
this.isShow = true
}

63
src/sse/SSEClient.js Normal file
View File

@ -0,0 +1,63 @@
import Bus from "@/assets/js/bus";
let eventSource = null;
let timer = null;
export function connectToSSE(username) {
if (typeof (EventSource) !== 'undefined') {
const url = `/api/events?username=${username}`;
eventSource = new EventSource(url);
eventSource.addEventListener('message', function (event) {
const msg = JSON.parse( event.data);
onMessage(msg)
});
eventSource.addEventListener('error', function (event) {
eventSource.close()
connectToSSE(username)
});
timer = setInterval(() => {
if (eventSource.readyState === 2) {
connectToSSE(username);
}
}, 15000);
} else {
console.error('EventSource is not supported by the browser');
}
}
function onMessage(msg) {
const url = msg.url
if (url === 'synced') {
Bus.$emit('msg/synced', msg)
} else {
Bus.$emit('msg/file/change', msg)
if ('operationFile' === url) {
let doc = msg.body
if (doc.code === 0) {
Bus.$notify({
title: `${doc.operation}成功`,
dangerouslyUseHTMLString: true,
message: `
<div>
<p>form:</p>
<pre style="word-break: break-all;white-space: pre-wrap;font-size: 12px;">${doc.from}</pre>
</div>
<div>
<p>to:</p>
<pre style="word-break: break-all;white-space: pre-wrap;font-size: 12px;">${doc.to}</pre>
</div>`,
type: 'success',
});
} else {
Bus.$emit('msg/file/operation/fault', 'fault')
Bus.$notify({
title: `${doc.operation}失败`,
dangerouslyUseHTMLString: true,
message: `<span style="font-size: 12px;">${doc.msg}</span>`,
type: 'error'
});
}
}
}
}

View File

@ -20,8 +20,6 @@ import { resetRouter } from '@/router'
import router from '@/router'
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
import api from "@/api/file-api";
import {disconnect} from "@/websocket/sockJS";
const getDefaultState = () => {
return {
@ -179,7 +177,6 @@ const actions = {
logout({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
disconnect()
removeToken()
removeConsumerId()
removeRememberName()

View File

@ -1,83 +0,0 @@
import SockJS from 'sockjs-client';
import Stomp from './stomp-index';
import ws from './websocket_config';
import Bus from '@/assets/js/bus'
export function toConnection(username,token) {
connect(username, token);
// 断开重连机制,尝试发送消息,捕获异常发生时重连
ws.timer = setInterval(() => {
try {
if(ws.isConnected){
ws.stompClient.send("test");
}else{
connect(username, token);
}
} catch (err) {
connect(username, token);
}
}, 5000);
}
function connect(username,token){
//地址+端点路径,构建websocket链接地址,注意,对应config配置里的addEndpoint
let socket = new SockJS(ws.url + '/mq');
// 获取STOMP子协议的客户端对象
ws.stompClient = Stomp.over(socket);
// 定义客户端的认证信息,按需求配置
ws.headers = {
Authorization:token
};
// 向服务器发起websocket连接
ws.stompClient.connect(ws.headers,() => {
ws.isConnected = true;
// 订阅消息
ws.stompClient.subscribe('/user/queue/update', (msg) => {
const url = msg.headers.url
if (url === 'synced') {
Bus.$emit('msg/synced', msg)
} else {
Bus.$emit('msg/file/change', msg)
if ('operationFile' === url) {
let doc = JSON.parse(msg.body)
if (doc.code === 0) {
Bus.$notify({
title: `${doc.operation}成功`,
dangerouslyUseHTMLString: true,
message: `
<div>
<p>form:</p>
<pre style="word-break: break-all;white-space: pre-wrap;font-size: 12px;">${doc.from}</pre>
</div>
<div>
<p>to:</p>
<pre style="word-break: break-all;white-space: pre-wrap;font-size: 12px;">${doc.to}</pre>
</div>`,
type: 'success',
});
} else {
Bus.$emit('msg/file/operation/fault', 'fault')
Bus.$notify({
title: `${doc.operation}失败`,
dangerouslyUseHTMLString: true,
message: `<span style="font-size: 12px;">${doc.msg}</span>`,
type: 'error'
});
}
}
}
}, ws.headers);
}, (err) => {
ws.isConnected = false;
// 连接发生错误时的处理函数
});
}
export function disconnect() {
if (ws.isConnected) {
ws.stompClient.disconnect();
ws.isConnected = false
}
clearInterval(ws.timer)
}

View File

@ -1,6 +0,0 @@
var Stomp = require('./stomp.js');
var StompNode = require('./stomp-node.js');
module.exports = Stomp.Stomp;
module.exports.overTCP = StompNode.overTCP;
module.exports.overWS = StompNode.overWS;

View File

@ -1,113 +0,0 @@
// Generated by CoffeeScript 1.7.1
/*
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2013 [Jeff Mesnil](http://jmesnil.net/)
*/
(function() {
let net, overTCP, overWS, wrapTCP, wrapWS;
const Stomp = require('./stomp.js');
net = require('net');
Stomp.Stomp = window.Stomp
Stomp.Stomp.setInterval = function(interval, f) {
return setInterval(f, interval);
};
Stomp.Stomp.clearInterval = function(id) {
return clearInterval(id);
};
wrapTCP = function(port, host) {
var socket, ws;
socket = null;
ws = {
url: 'tcp:// ' + host + ':' + port,
send: function(d) {
return socket.write(d);
},
close: function() {
return socket.end();
}
};
socket = net.connect(port, host, function(e) {
return ws.onopen();
});
socket.on('error', function(e) {
return typeof ws.onclose === "function" ? ws.onclose(e) : void 0;
});
socket.on('close', function(e) {
return typeof ws.onclose === "function" ? ws.onclose(e) : void 0;
});
socket.on('data', function(data) {
var event;
event = {
'data': data.toString()
};
return ws.onmessage(event);
});
return ws;
};
wrapWS = function(url) {
var WebSocketClient, connection, socket, ws;
WebSocketClient = require('websocket').client;
connection = null;
ws = {
url: url,
send: function(d) {
return connection.sendUTF(d);
},
close: function() {
return connection.close();
}
};
socket = new WebSocketClient();
socket.on('connect', function(conn) {
connection = conn;
ws.onopen();
connection.on('error', function(error) {
return typeof ws.onclose === "function" ? ws.onclose(error) : void 0;
});
connection.on('close', function() {
return typeof ws.onclose === "function" ? ws.onclose() : void 0;
});
return connection.on('message', function(message) {
var event;
if (message.type === 'utf8') {
event = {
'data': message.utf8Data
};
return ws.onmessage(event);
}
});
});
socket.connect(url);
return ws;
};
overTCP = function(host, port) {
var socket;
socket = wrapTCP(port, host);
return Stomp.Stomp.over(socket);
};
overWS = function(url) {
var socket;
socket = wrapWS(url);
return Stomp.Stomp.over(socket);
};
if (typeof exports !== "undefined" && exports !== null) {
exports.overTCP = overTCP;
exports.overWS = overWS;
}
}).call(this);

View File

@ -1,488 +0,0 @@
// Generated by CoffeeScript 1.7.1
/*
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2010-2013 [Jeff Mesnil](http://jmesnil.net/)
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
*/
(function() {
var Byte, Client, Frame, Stomp,
__hasProp = {}.hasOwnProperty,
__slice = [].slice;
Byte = {
LF: '\x0A',
NULL: '\x00'
};
Frame = (function() {
var unmarshallSingle;
function Frame(command, headers, body) {
this.command = command;
this.headers = headers != null ? headers : {};
this.body = body != null ? body : '';
}
Frame.prototype.toString = function() {
var lines, name, skipContentLength, value, _ref;
lines = [this.command];
skipContentLength = this.headers['content-length'] === false ? true : false;
if (skipContentLength) {
delete this.headers['content-length'];
}
_ref = this.headers;
for (name in _ref) {
if (!__hasProp.call(_ref, name)) continue;
value = _ref[name];
lines.push("" + name + ":" + value);
}
if (this.body && !skipContentLength) {
lines.push("content-length:" + (Frame.sizeOfUTF8(this.body)));
}
lines.push(Byte.LF + this.body);
return lines.join(Byte.LF);
};
Frame.sizeOfUTF8 = function(s) {
if (s) {
return encodeURI(s).match(/%..|./g).length;
} else {
return 0;
}
};
unmarshallSingle = function(data) {
var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;
divider = data.search(RegExp("" + Byte.LF + Byte.LF));
headerLines = data.substring(0, divider).split(Byte.LF);
command = headerLines.shift();
headers = {};
trim = function(str) {
return str.replace(/^\s+|\s+$/g, '');
};
_ref = headerLines.reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
idx = line.indexOf(':');
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
}
body = '';
start = divider + 2;
if (headers['content-length']) {
len = parseInt(headers['content-length']);
body = ('' + data).substring(start, start + len);
} else {
chr = null;
for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {
chr = data.charAt(i);
if (chr === Byte.NULL) {
break;
}
body += chr;
}
}
return new Frame(command, headers, body);
};
Frame.unmarshall = function(datas) {
var data;
return (function() {
var _i, _len, _ref, _results;
_ref = datas.split(RegExp("" + Byte.NULL + Byte.LF + "*"));
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
data = _ref[_i];
if ((data != null ? data.length : void 0) > 0) {
_results.push(unmarshallSingle(data));
}
}
return _results;
})();
};
Frame.marshall = function(command, headers, body) {
var frame;
frame = new Frame(command, headers, body);
return frame.toString() + Byte.NULL;
};
return Frame;
})();
Client = (function() {
var now;
function Client(ws) {
this.ws = ws;
this.ws.binaryType = "arraybuffer";
this.counter = 0;
this.connected = false;
this.heartbeat = {
outgoing: 10000,
incoming: 10000
};
this.maxWebSocketFrameSize = 16 * 1024;
this.subscriptions = {};
}
Client.prototype.debug = function(message) {
var _ref;
return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? void 0 : void 0 : void 0;
};
now = function() {
if (Date.now) {
return Date.now();
} else {
return new Date().valueOf;
}
};
Client.prototype._transmit = function(command, headers, body) {
var out;
out = Frame.marshall(command, headers, body);
if (typeof this.debug === "function") {
this.debug(">>> " + out);
}
while (true) {
if (out.length > this.maxWebSocketFrameSize) {
this.ws.send(out.substring(0, this.maxWebSocketFrameSize));
out = out.substring(this.maxWebSocketFrameSize);
if (typeof this.debug === "function") {
this.debug("remaining = " + out.length);
}
} else {
return this.ws.send(out);
}
}
};
Client.prototype._setupHeartbeat = function(headers) {
var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;
if ((_ref = headers.version) !== Stomp.VERSIONS.V1_1 && _ref !== Stomp.VERSIONS.V1_2) {
return;
}
_ref1 = (function() {
var _i, _len, _ref1, _results;
_ref1 = headers['heart-beat'].split(",");
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
_results.push(parseInt(v));
}
return _results;
})(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];
if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {
ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
if (typeof this.debug === "function") {
this.debug("send PING every " + ttl + "ms");
}
this.pinger = Stomp.setInterval(ttl, (function(_this) {
return function() {
_this.ws.send(Byte.LF);
return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;
};
})(this));
}
if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {
ttl = Math.max(this.heartbeat.incoming, serverOutgoing);
if (typeof this.debug === "function") {
this.debug("check PONG every " + ttl + "ms");
}
return this.ponger = Stomp.setInterval(ttl, (function(_this) {
return function() {
var delta;
delta = now() - _this.serverActivity;
if (delta > ttl * 2) {
if (typeof _this.debug === "function") {
_this.debug("did not receive server activity for the last " + delta + "ms");
}
return _this.ws.close();
}
};
})(this));
}
};
Client.prototype._parseConnect = function() {
var args, connectCallback, errorCallback, headers;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
headers = {};
switch (args.length) {
case 2:
headers = args[0], connectCallback = args[1];
break;
case 3:
if (args[1] instanceof Function) {
headers = args[0], connectCallback = args[1], errorCallback = args[2];
} else {
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];
}
break;
case 4:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];
break;
default:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];
}
return [headers, connectCallback, errorCallback];
};
Client.prototype.connect = function() {
var args, errorCallback, headers, out;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
out = this._parseConnect.apply(this, args);
headers = out[0], this.connectCallback = out[1], errorCallback = out[2];
if (typeof this.debug === "function") {
this.debug("Opening Web Socket...");
}
this.ws.onmessage = (function(_this) {
return function(evt) {
var arr, c, client, data, frame, messageID, onreceive, subscription, _i, _len, _ref, _results;
data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = arr.length; _i < _len; _i++) {
c = arr[_i];
_results.push(String.fromCharCode(c));
}
return _results;
})()).join('')) : evt.data;
_this.serverActivity = now();
if (data === Byte.LF) {
if (typeof _this.debug === "function") {
_this.debug("<<< PONG");
}
return;
}
if (typeof _this.debug === "function") {
_this.debug("<<< " + data);
}
_ref = Frame.unmarshall(data);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
frame = _ref[_i];
switch (frame.command) {
case "CONNECTED":
if (typeof _this.debug === "function") {
_this.debug("connected to server " + frame.headers.server);
}
_this.connected = true;
_this._setupHeartbeat(frame.headers);
_results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);
break;
case "MESSAGE":
subscription = frame.headers.subscription;
onreceive = _this.subscriptions[subscription] || _this.onreceive;
if (onreceive) {
client = _this;
messageID = frame.headers["message-id"];
frame.ack = function(headers) {
if (headers == null) {
headers = {};
}
return client.ack(messageID, subscription, headers);
};
frame.nack = function(headers) {
if (headers == null) {
headers = {};
}
return client.nack(messageID, subscription, headers);
};
_results.push(onreceive(frame));
} else {
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);
}
break;
case "RECEIPT":
_results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);
break;
case "ERROR":
_results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);
break;
default:
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);
}
}
return _results;
};
})(this);
this.ws.onclose = (function(_this) {
return function() {
var msg;
msg = "Whoops! Lost connection to " + _this.ws.url;
if (typeof _this.debug === "function") {
_this.debug(msg);
}
_this._cleanUp();
return typeof errorCallback === "function" ? errorCallback(msg) : void 0;
};
})(this);
return this.ws.onopen = (function(_this) {
return function() {
if (typeof _this.debug === "function") {
_this.debug('Web Socket Opened...');
}
headers["accept-version"] = Stomp.VERSIONS.supportedVersions();
headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');
return _this._transmit("CONNECT", headers);
};
})(this);
};
Client.prototype.disconnect = function(disconnectCallback, headers) {
if (headers == null) {
headers = {};
}
this._transmit("DISCONNECT", headers);
this.ws.onclose = null;
this.ws.close();
this._cleanUp();
return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;
};
Client.prototype._cleanUp = function() {
this.connected = false;
if (this.pinger) {
Stomp.clearInterval(this.pinger);
}
if (this.ponger) {
return Stomp.clearInterval(this.ponger);
}
};
Client.prototype.send = function(destination, headers, body) {
if (headers == null) {
headers = {};
}
if (body == null) {
body = '';
}
headers.destination = destination;
return this._transmit("SEND", headers, body);
};
Client.prototype.subscribe = function(destination, callback, headers) {
var client;
if (headers == null) {
headers = {};
}
if (!headers.id) {
headers.id = "sub-" + this.counter++;
}
headers.destination = destination;
this.subscriptions[headers.id] = callback;
this._transmit("SUBSCRIBE", headers);
client = this;
return {
id: headers.id,
unsubscribe: function() {
return client.unsubscribe(headers.id);
}
};
};
Client.prototype.unsubscribe = function(id) {
delete this.subscriptions[id];
return this._transmit("UNSUBSCRIBE", {
id: id
});
};
Client.prototype.begin = function(transaction) {
var client, txid;
txid = transaction || "tx-" + this.counter++;
this._transmit("BEGIN", {
transaction: txid
});
client = this;
return {
id: txid,
commit: function() {
return client.commit(txid);
},
abort: function() {
return client.abort(txid);
}
};
};
Client.prototype.commit = function(transaction) {
return this._transmit("COMMIT", {
transaction: transaction
});
};
Client.prototype.abort = function(transaction) {
return this._transmit("ABORT", {
transaction: transaction
});
};
Client.prototype.ack = function(messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("ACK", headers);
};
Client.prototype.nack = function(messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("NACK", headers);
};
return Client;
})();
Stomp = {
VERSIONS: {
V1_0: '1.0',
V1_1: '1.1',
V1_2: '1.2',
supportedVersions: function() {
return '1.1,1.0';
}
},
client: function(url, protocols) {
var klass, ws;
if (protocols == null) {
protocols = ['v10.stomp', 'v11.stomp'];
}
klass = Stomp.WebSocketClass || WebSocket;
ws = new klass(url, protocols);
return new Client(ws);
},
over: function(ws) {
return new Client(ws);
},
Frame: Frame
};
if (typeof exports !== "undefined" && exports !== null) {
exports.Stomp = Stomp;
}
if (typeof window !== "undefined" && window !== null) {
Stomp.setInterval = function(interval, f) {
return window.setInterval(f, interval);
};
Stomp.clearInterval = function(id) {
return window.clearInterval(id);
};
window.Stomp = Stomp;
} else if (!exports) {
self.Stomp = Stomp;
}
}).call(this);

View File

@ -1,19 +0,0 @@
let host = window.location.host;
let url = `${document.location.protocol}//${host}`;
if(process.env.NODE_ENV === 'development'){
if (window.location.port.length > 0) {
host = window.location.host.substring(0, window.location.host.length - window.location.port.length - 1)
}
url = `${document.location.protocol}//${host}:8088`;
}
let stompClient = '';
let isConnected = false;
let timer = '';
export default {
stompClient,
timer,
url,
isConnected,
}