Auto-reconnect

This commit is contained in:
gparant 2020-05-13 20:22:42 +02:00
parent dd5a0c9933
commit ec297e3912
7 changed files with 118 additions and 15 deletions

View File

@ -37,6 +37,9 @@ export class IoSocketController {
if (!socket.handshake.query || !socket.handshake.query.token) { if (!socket.handshake.query || !socket.handshake.query.token) {
return next(new Error('Authentication error')); return next(new Error('Authentication error'));
} }
if(this.searchClientByToken(socket.handshake.query.token)){
return next(new Error('Authentication error'));
}
Jwt.verify(socket.handshake.query.token, SECRET_KEY, (err: JsonWebTokenError, tokenDecoded: object) => { Jwt.verify(socket.handshake.query.token, SECRET_KEY, (err: JsonWebTokenError, tokenDecoded: object) => {
if (err) { if (err) {
return next(new Error('Authentication error')); return next(new Error('Authentication error'));
@ -206,6 +209,21 @@ export class IoSocketController {
return null; return null;
} }
/**
* @param userId
*/
searchClientByToken(userId: string): ExSocketInterface | null {
let clients: Array<any> = Object.values(this.Io.sockets.sockets);
for (let i = 0; i < clients.length; i++) {
let client: ExSocketInterface = clients[i];
if (client.userId !== userId) {
continue
}
return client;
}
return null;
}
/** /**
* *
* @param Client: ExSocketInterface * @param Client: ExSocketInterface

View File

@ -9,7 +9,7 @@
<link rel="stylesheet" href="/resources/style/style.css"> <link rel="stylesheet" href="/resources/style/style.css">
<title>Document</title> <title>Document</title>
</head> </head>
<body style="margin: 0"> <body id="body" style="margin: 0">
<script src="bundle.js"></script> <script src="bundle.js"></script>
<div id="webRtc" class="webrtc"> <div id="webRtc" class="webrtc">
<div id="activeCam" class="activeCam"> <div id="activeCam" class="activeCam">

View File

@ -1,6 +1,28 @@
body{ body{
overflow: hidden; overflow: hidden;
} }
body .message-info{
width: 20%;
height: auto;
min-height: 30px;
position: absolute;
top: 5px;
left: 40%;
padding-top: 10px;
text-align: center;
}
body .message-info.error{
background: red;
}
body .message-info.success{
background: green;
}
body .message-info.info{
background: dodgerblue;
}
body .message-info.warning{
background: #ffa500d6;
}
video{ video{
-webkit-transform: scaleX(-1); -webkit-transform: scaleX(-1);
transform: scaleX(-1); transform: scaleX(-1);

View File

@ -4,6 +4,7 @@ const SocketIo = require('socket.io-client');
import Axios from "axios"; import Axios from "axios";
import {API_URL} from "./Enum/EnvironmentVariable"; import {API_URL} from "./Enum/EnvironmentVariable";
import {getMapKeyByUrl} from "./Phaser/Login/LogincScene"; import {getMapKeyByUrl} from "./Phaser/Login/LogincScene";
import {MessageUI} from "./Logger/MessageUI";
enum EventMessage{ enum EventMessage{
WEBRTC_SIGNAL = "webrtc-signal", WEBRTC_SIGNAL = "webrtc-signal",
@ -15,6 +16,9 @@ enum EventMessage{
WEBRTC_DISCONNECT = "webrtc-disconect", WEBRTC_DISCONNECT = "webrtc-disconect",
GROUP_CREATE_UPDATE = "group-create-update", GROUP_CREATE_UPDATE = "group-create-update",
GROUP_DELETE = "group-delete", GROUP_DELETE = "group-delete",
CONNECT_ERROR = "connect_error",
RECONNECT = "reconnect"
} }
class Message { class Message {
@ -169,6 +173,8 @@ export class Connexion implements ConnexionInterface {
GameManager: GameManager; GameManager: GameManager;
lastPositionShared: MessageUserPosition = null;
constructor(email : string, GameManager: GameManager) { constructor(email : string, GameManager: GameManager) {
this.email = email; this.email = email;
this.GameManager = GameManager; this.GameManager = GameManager;
@ -189,18 +195,7 @@ export class Connexion implements ConnexionInterface {
} }
}); });
//join the room this.connectSocketServer();
//this.joinARoom(this.startedRoom, characterSelected);
//share your first position
//this.sharePosition(0, 0, characterSelected, this.startedRoom);
this.positionOfAllUser();
this.errorMessage();
this.groupUpdatedOrCreated();
this.groupDeleted();
return res.data; return res.data;
}) })
@ -210,6 +205,37 @@ export class Connexion implements ConnexionInterface {
}); });
} }
/**
*
* @param character
*/
connectSocketServer(character : string = null){
//if try to reconnect with last position
if(this.lastPositionShared) {
//join the room
this.joinARoom(
this.lastPositionShared.roomId,
this.lastPositionShared.character
);
//share your first position
this.sharePosition(
this.lastPositionShared ? this.lastPositionShared.position.x : 0,
this.lastPositionShared ? this.lastPositionShared.position.y : 0,
this.lastPositionShared.character,
this.lastPositionShared.roomId,
this.lastPositionShared.position.direction
);
}
//listen event
this.positionOfAllUser();
this.disconnectServer();
this.errorMessage();
this.groupUpdatedOrCreated();
this.groupDeleted();
}
//TODO add middleware with access token to secure api //TODO add middleware with access token to secure api
loadMaps() : Promise<any> { loadMaps() : Promise<any> {
return Axios.get(`${API_URL}/maps`) return Axios.get(`${API_URL}/maps`)
@ -256,6 +282,7 @@ export class Connexion implements ConnexionInterface {
this.email, this.email,
character character
); );
this.lastPositionShared = messageUserPosition;
this.socket.emit(EventMessage.USER_POSITION, messageUserPosition.toString()); this.socket.emit(EventMessage.USER_POSITION, messageUserPosition.toString());
} }
@ -319,6 +346,17 @@ export class Connexion implements ConnexionInterface {
}) })
} }
disconnectServer(): void {
this.socket.on(EventMessage.CONNECT_ERROR, () => {
MessageUI.warningMessage("Trying to connect!");
});
this.socket.on(EventMessage.RECONNECT, () => {
MessageUI.removeMessage();
this.connectSocketServer();
});
}
disconnectMessage(callback: Function): void { disconnectMessage(callback: Function): void {
this.socket.on(EventMessage.WEBRTC_DISCONNECT, callback); this.socket.on(EventMessage.WEBRTC_DISCONNECT, callback);
} }

View File

@ -0,0 +1,27 @@
export class MessageUI {
static warningMessage(text: string){
this.removeMessage();
let body = document.getElementById("body");
body.insertAdjacentHTML('afterbegin', `
<div id="message-reconnect" class="message-info warning">
${text}
</div>
`);
}
static removeMessage(id : string = null) {
if(!id){
let messages = document.getElementsByClassName("message-info");
for (let i = 0; i < messages.length; i++){
messages.item(i).remove();
}
return;
}
let previousElement = document.getElementById(id);
if (!previousElement) {
return;
}
previousElement.remove();
}
}

View File

@ -185,7 +185,6 @@ export class GameScene extends Phaser.Scene implements GameSceneInterface, Creat
// TODO: eventually compute a relative URL // TODO: eventually compute a relative URL
let absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href; let absoluteExitSceneUrl = new URL(exitSceneUrl, this.MapUrlFile).href;
console.log('absoluteExitSceneUrl ', absoluteExitSceneUrl);
let exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene); let exitSceneKey = gameManager.loadMap(absoluteExitSceneUrl, this.scene);
let tiles : any = layer.data; let tiles : any = layer.data;

View File

@ -13,7 +13,6 @@ export function getMapKeyByUrl(mapUrlStart: string){
// FIXME: the key should be computed from the full URL of the map. // FIXME: the key should be computed from the full URL of the map.
let startPos = mapUrlStart.indexOf('://')+3; let startPos = mapUrlStart.indexOf('://')+3;
let endPos = mapUrlStart.indexOf(".json"); let endPos = mapUrlStart.indexOf(".json");
console.log('MAP KEY '+mapUrlStart.substring(startPos, endPos));
return mapUrlStart.substring(startPos, endPos); return mapUrlStart.substring(startPos, endPos);