improved the unloading process to not create a useless socket

This commit is contained in:
kharhamel 2021-03-26 14:12:22 +01:00
parent 30e12702eb
commit 886daebfea
6 changed files with 26 additions and 22 deletions

View File

@ -77,10 +77,10 @@ export class SocketManager {
} }
public async handleJoinRoom(socket: UserSocket, joinRoomMessage: JoinRoomMessage): Promise<{ room: GameRoom; user: User }> { public async handleJoinRoom(socket: UserSocket, joinRoomMessage: JoinRoomMessage): Promise<{ room: GameRoom; user: User }> {
//join new previous room //join new previous room
const {room, user} = await this.joinRoom(socket, joinRoomMessage); const {room, user} = await this.joinRoom(socket, joinRoomMessage);
const roomJoinedMessage = new RoomJoinedMessage(); const roomJoinedMessage = new RoomJoinedMessage();
roomJoinedMessage.setTagList(joinRoomMessage.getTagList()); roomJoinedMessage.setTagList(joinRoomMessage.getTagList());

View File

@ -53,10 +53,8 @@ services:
pusher: pusher:
image: thecodingmachine/nodejs:12 image: thecodingmachine/nodejs:12
command: yarn dev command: yarn dev
#command: yarn run prod
#command: yarn run profile
environment: environment:
DEBUG: "*" DEBUG: "socket:*"
STARTUP_COMMAND_1: yarn install STARTUP_COMMAND_1: yarn install
SECRET_JITSI_KEY: "$SECRET_JITSI_KEY" SECRET_JITSI_KEY: "$SECRET_JITSI_KEY"
SECRET_KEY: yourSecretKey SECRET_KEY: yourSecretKey

View File

@ -6,16 +6,25 @@ import {GameConnexionTypes, urlManager} from "../Url/UrlManager";
import {localUserStore} from "./LocalUserStore"; import {localUserStore} from "./LocalUserStore";
import {LocalUser} from "./LocalUser"; import {LocalUser} from "./LocalUser";
import {Room} from "./Room"; import {Room} from "./Room";
import {Subject} from "rxjs";
import {ServerToClientMessage} from "../Messages/generated/messages_pb";
class ConnectionManager { class ConnectionManager {
private localUser!:LocalUser; private localUser!:LocalUser;
private connexionType?: GameConnexionTypes private connexionType?: GameConnexionTypes
private reconnectingTimeout: NodeJS.Timeout|null = null;
private _unloading:boolean = false;
public _serverToClientMessageStream:Subject<ServerToClientMessage> = new Subject(); get unloading () {
return this._unloading;
}
constructor() {
window.addEventListener('beforeunload', () => {
this._unloading = true;
if (this.reconnectingTimeout) clearTimeout(this.reconnectingTimeout)
})
}
/** /**
* Tries to login to the node server and return the starting map url to be loaded * Tries to login to the node server and return the starting map url to be loaded
*/ */
@ -99,7 +108,7 @@ class ConnectionManager {
}).catch((err) => { }).catch((err) => {
// Let's retry in 4-6 seconds // Let's retry in 4-6 seconds
return new Promise<OnConnectInterface>((resolve, reject) => { return new Promise<OnConnectInterface>((resolve, reject) => {
setTimeout(() => { this.reconnectingTimeout = setTimeout(() => {
//todo: allow a way to break recursion? //todo: allow a way to break recursion?
//todo: find a way to avoid recursive function. Otherwise, the call stack will grow indefinitely. //todo: find a way to avoid recursive function. Otherwise, the call stack will grow indefinitely.
this.connectToRoomSocket(roomId, name, characterLayers, position, viewport).then((connection) => resolve(connection)); this.connectToRoomSocket(roomId, name, characterLayers, position, viewport).then((connection) => resolve(connection));

View File

@ -45,6 +45,7 @@ import {BodyResourceDescriptionInterface} from "../Phaser/Entity/PlayerTextures"
import {adminMessagesService} from "./AdminMessagesService"; import {adminMessagesService} from "./AdminMessagesService";
import {worldFullMessageStream} from "./WorldFullMessageStream"; import {worldFullMessageStream} from "./WorldFullMessageStream";
import {worldFullWarningStream} from "./WorldFullWarningStream"; import {worldFullWarningStream} from "./WorldFullWarningStream";
import {connectionManager} from "./ConnectionManager";
const manualPingDelay = 20000; const manualPingDelay = 20000;
@ -380,10 +381,7 @@ export class RoomConnection implements RoomConnection {
public onConnectError(callback: (error: Event) => void): void { public onConnectError(callback: (error: Event) => void): void {
this.socket.addEventListener('error', callback) this.socket.addEventListener('error', callback)
} }
/*public onConnect(callback: (e: Event) => void): void {
this.socket.addEventListener('open', callback)
}*/
public onConnect(callback: (roomConnection: OnConnectInterface) => void): void { public onConnect(callback: (roomConnection: OnConnectInterface) => void): void {
//this.socket.addEventListener('open', callback) //this.socket.addEventListener('open', callback)
this.onMessage(EventMessage.CONNECT, callback); this.onMessage(EventMessage.CONNECT, callback);
@ -452,9 +450,9 @@ export class RoomConnection implements RoomConnection {
}); });
} }
public onServerDisconnected(callback: (event: CloseEvent) => void): void { public onServerDisconnected(callback: () => void): void {
this.socket.addEventListener('close', (event) => { this.socket.addEventListener('close', (event) => {
if (this.closed === true) { if (this.closed === true || connectionManager.unloading) {
return; return;
} }
console.log('Socket closed with code '+event.code+". Reason: "+event.reason); console.log('Socket closed with code '+event.code+". Reason: "+event.reason);
@ -462,7 +460,7 @@ export class RoomConnection implements RoomConnection {
// Normal closure case // Normal closure case
return; return;
} }
callback(event); callback();
}); });
} }

View File

@ -471,9 +471,7 @@ export class GameScene extends ResizableScene implements CenterListener {
this.connection.onServerDisconnected(() => { this.connection.onServerDisconnected(() => {
console.log('Player disconnected from server. Reloading scene.'); console.log('Player disconnected from server. Reloading scene.');
this.cleanupClosingScene();
this.simplePeer.closeAllConnections();
this.simplePeer.unregister();
const gameSceneKey = 'somekey' + Math.round(Math.random() * 10000); const gameSceneKey = 'somekey' + Math.round(Math.random() * 10000);
const game: Phaser.Scene = new GameScene(this.room, this.MapUrlFile, gameSceneKey); const game: Phaser.Scene = new GameScene(this.room, this.MapUrlFile, gameSceneKey);
@ -708,6 +706,7 @@ export class GameScene extends ResizableScene implements CenterListener {
audioManager.unloadAudio(); audioManager.unloadAudio();
// We are completely destroying the current scene to avoid using a half-backed instance when coming back to the same map. // We are completely destroying the current scene to avoid using a half-backed instance when coming back to the same map.
this.connection?.closeConnection(); this.connection?.closeConnection();
this.simplePeer.closeAllConnections();
this.simplePeer?.unregister(); this.simplePeer?.unregister();
this.messageSubscription?.unsubscribe(); this.messageSubscription?.unsubscribe();
} }

View File

@ -1,5 +1,4 @@
import {HttpRequest, HttpResponse} from "uWebSockets.js"; import {HttpResponse} from "uWebSockets.js";
import {ADMIN_API_TOKEN} from "../Enum/EnvironmentVariable";
export class BaseController { export class BaseController {
@ -14,7 +13,8 @@ export class BaseController {
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
protected errorToResponse(e: any, res: HttpResponse): void { protected errorToResponse(e: any, res: HttpResponse): void {
console.error("An error happened", e); console.error(e.message || "An error happened.", e?.config.url);
console.error(e.stack || 'no stack defined.');
if (e.response) { if (e.response) {
res.writeStatus(e.response.status+" "+e.response.statusText); res.writeStatus(e.response.status+" "+e.response.statusText);
this.addCorsHeaders(res); this.addCorsHeaders(res);