This commit is contained in:
2026-03-12 23:21:01 +08:00
parent 9df4021d68
commit bd0ce0058e
2 changed files with 27 additions and 1 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "@kevisual/remote-app", "name": "@kevisual/remote-app",
"version": "0.0.6", "version": "0.0.7",
"description": "", "description": "",
"main": "dist/app.js", "main": "dist/app.js",
"scripts": { "scripts": {

View File

@@ -41,6 +41,8 @@ export class RemoteApp {
reconnectAttempts: number = 0; reconnectAttempts: number = 0;
reconnectTimer: NodeJS.Timeout | null = null; reconnectTimer: NodeJS.Timeout | null = null;
isManuallyClosed: boolean = false; isManuallyClosed: boolean = false;
isInitializing: boolean = false;
private initId: number = 0;
constructor(opts?: RemoteAppOptions) { constructor(opts?: RemoteAppOptions) {
this.mainApp = opts?.app; this.mainApp = opts?.app;
const token = opts.token; const token = opts.token;
@@ -115,10 +117,18 @@ export class RemoteApp {
return wsURL; return wsURL;
} }
async init() { async init() {
// 防止重复初始化
if (this.isInitializing) {
return;
}
this.isInitializing = true;
const currentInitId = ++this.initId;
if (!this.url) { if (!this.url) {
this.isInitializing = false;
throw new Error('No url provided for remote app'); throw new Error('No url provided for remote app');
} }
if (!this.id) { if (!this.id) {
this.isInitializing = false;
throw new Error('No id provided for remote app'); throw new Error('No id provided for remote app');
} }
this.isError = false; this.isError = false;
@@ -129,11 +139,22 @@ export class RemoteApp {
const ws = new WebSocket(this.getWsURL(this.url)); const ws = new WebSocket(this.getWsURL(this.url));
const that = this; const that = this;
ws.onopen = function () { ws.onopen = function () {
// 检查是否是最新的连接
if (currentInitId !== that.initId) {
ws.close();
return;
}
that.isConnected = true; that.isConnected = true;
that.isInitializing = false;
that.onOpen(); that.onOpen();
console.log('[remote-app] WebSocket connection opened'); console.log('[remote-app] WebSocket connection opened');
}; };
ws.onclose = function () { ws.onclose = function () {
// 检查是否是最新的连接
if (currentInitId !== that.initId) {
return;
}
that.isInitializing = false;
that.isConnected = false; that.isConnected = false;
that.onClose(); that.onClose();
} }
@@ -141,6 +162,11 @@ export class RemoteApp {
that.onMessage(event.data); that.onMessage(event.data);
} }
ws.onerror = function (error) { ws.onerror = function (error) {
// 检查是否是最新的连接
if (currentInitId !== that.initId) {
return;
}
that.isInitializing = false;
that.onError(error); that.onError(error);
} }
this.ws = ws; this.ws = ws;