Skip to content

Commit

Permalink
Merge pull request #269 from computas/SP24-772-websocket-error
Browse files Browse the repository at this point in the history
Sp24 772 websocket error
  • Loading branch information
Ivan-Computas authored Sep 18, 2024
2 parents bcd666a + 3e4ab2e commit 8985571
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 14 deletions.
3 changes: 0 additions & 3 deletions src/app/game/game-multiplayer/lobby/lobby.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@ export class LobbyComponent implements OnInit, OnDestroy {
) {}

ngOnInit(): void {
if (this.initializeComponent) {
this.initializeComponent();
}
const difficulty = 2; // Difficulty set to medium (1 for easy, 3 for hard)
this.subscriptions.add(this.multiPlayerService.joinGame(difficulty).subscribe());
this.subscriptions.add(
Expand Down
3 changes: 1 addition & 2 deletions src/app/game/game-multiplayer/multiplayer.component.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { trigger, style, animate, transition } from '@angular/animations';
import { Router } from '@angular/router';

import { MultiplayerService } from '../services/multiplayer.service';
import { WebSocketService } from '../services/web-socket.service';
import { Subscription } from 'rxjs';
Expand Down Expand Up @@ -103,7 +102,7 @@ export class MultiplayerComponent implements OnInit, OnDestroy {

ngOnDestroy(): void {
this.webSocketService.disconnect();
this.multiplayerService.resetStateInfo();
this.multiplayerService.clearState();
this.subs.unsubscribe();
}
}
5 changes: 0 additions & 5 deletions src/app/game/services/multiplayer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@ export class MultiplayerService {
private translationService: TranslationService
) {}

resetStateInfo() {
this.stateInfo = this.initialState;
}

joinGame(difficulty_id: number) {
this.webSocketService.emit(
SocketEndpoints.JOIN_GAME,
Expand Down Expand Up @@ -215,7 +211,6 @@ export class MultiplayerService {

clearState() {
this.stateInfo = this.initialState;
this.webSocketService.disconnect();
}

changestate(gameState: GAMESTATE) {
Expand Down
66 changes: 62 additions & 4 deletions src/app/game/services/web-socket.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { io, Socket } from 'socket.io-client';
import { Router } from '@angular/router';
import { environment } from '@/environments/environment';
import { SocketEndpoints } from '@/app/shared/models/websocketEndpoints';
import { PlayerDisconnectedData } from '@/app/shared/models/interfaces';
Expand All @@ -11,27 +12,55 @@ import { GameStateService } from '../services/game-state-service';
})
export class WebSocketService {
socket: Socket | undefined;
private retryAttempts = 0;
private maxRetries = 5;
private retryDelay = 3000;

playerDisconnectedData: PlayerDisconnectedData | undefined;

private readonly _playerDisconnected = new BehaviorSubject<boolean>(false);
readonly playerDisconnected$ = this._playerDisconnected.asObservable();
private isConnected = false;
private isRetrying = false;

constructor(private gameStateService: GameStateService) {}

constructor(private gameStateService: GameStateService, private router: Router) {}

startSockets() {
this.socket = io(environment.WS_ENDPOINT);
if (this.socket && this.socket.connected) {
console.warn('Socket already connected');
return;
}

if (this.isRetrying) {
console.warn('Currently retrying connection; will not start a new connection.');
return;
}

this.isRetrying = true;
this.socket = io(environment.TEKNISKBACKEND_ENDPOINT);

this.socket.on('connect', () => {
this.isConnected = true;
})

this.socket.on('connect_failed', () => {
console.error('connect_failed');
this.handleConnectionError();

});

this.socket.on('connect_error', (error) => {
console.error(error);
this.handleConnectionError();
});

this.socket.on('disconnect', (reason) => {
this.socket.on('disconnect', (reason: any) => {
console.warn('disconnected', reason);
this.isConnected = false;
if (reason !== "io client disconnect") {
this.handleConnectionError();
}
});
this.socket.on('error', (reason) => {
console.error('error', reason);
Expand All @@ -47,10 +76,19 @@ export class WebSocketService {
}

disconnect() {
if (this.socket && !this.socket.disconnected) {
if (this.socket && ! this.socket.disconnected) {
console.warn('socket disconnecting and removing listener');
this.socket.removeAllListeners();
this.socket.disconnect();
this.socket = undefined;
this.isConnected = false;
this.isRetrying = false;
console.log("Websocket closed properly")
this.retryAttempts = 0;
} else if (this.socket) {
this.socket.removeAllListeners();
this.socket.disconnect();
console.log("Websocket closed properly without ever being connected")
}
}

Expand All @@ -75,4 +113,24 @@ export class WebSocketService {
set playerDisconnected(val: boolean) {
this._playerDisconnected.next(val);
}

handleConnectionError() {
this.retryAttempts++;

if (this.retryAttempts <= this.maxRetries) {
console.warn(`Retrying connection... Attempt ${this.retryAttempts}/${this.maxRetries}`);
setTimeout(() => {
this.startSockets();
}, this.retryDelay);
} else {
console.error('Max retry attempts reached. Redirecting to welcome page.');
this.redirectToWelcomePage();
}
}

redirectToWelcomePage() {
this.disconnect();
this.router.navigate(['/welcome'])
}
}

0 comments on commit 8985571

Please sign in to comment.