Skip to content

Commit 9d7e2e3

Browse files
coder-pmMarcin Polak
authored andcommitted
Implemented latency measuring
1 parent 1e91dcd commit 9d7e2e3

File tree

4 files changed

+53
-15
lines changed

4 files changed

+53
-15
lines changed

package-lock.json

Lines changed: 32 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,18 @@
22
"name": "battle-city-react-server",
33
"private": true,
44
"dependencies": {
5+
"lodash.debounce": "^4.0.8",
56
"socket.io": "^2.2.0",
67
"uuid": "^3.3.2"
78
},
89
"devDependencies": {
9-
"@types/node": "^11.13.7",
10+
"@types/lodash.debounce": "^4.0.6",
11+
"@types/node": "^11.13.10",
1012
"@types/socket.io": "^2.1.2",
1113
"@types/uuid": "^3.4.4",
12-
"nodemon": "^1.18.11",
14+
"nodemon": "^1.19.0",
1315
"ts-node": "^8.1.0",
14-
"typescript": "^3.4.4"
16+
"typescript": "^3.4.5"
1517
},
1618
"scripts": {
1719
"start": "npm run build:live",

src/game/enums/NetworkPacket.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ export enum NetworkPacket {
66
CONNECT_ERROR = 'connect_error',
77
DISCONNECT = 'disconnect',
88
GAME_HANDSHAKING = 'game.handshaking',
9+
GAME_PING = 'game.ping',
10+
GAME_PONG = 'game.pong',
911
BOARD_STATE_OBSTACLES = 'board.state.obstacles',
1012
BOARD_STATE_TANKS = 'board.state.tanks',
1113
BOARD_STATE_MISSILES = 'board.state.missiles',

src/server/classes/Game/Game.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {GAME_FRAMERATE, GAME_SERVER_ADDRESS, GAME_SERVER_PORT, TANK_HEIGHT, TANK_WIDTH} from "../../../constants";
22
import World from "../../../game/classes/World";
33
import uuidv4 from 'uuid/v4';
4+
import debounce from 'lodash.debounce';
45
import SocketIO from 'socket.io';
56
import http, {Server} from "http";
67
import {NetworkPacket} from "../../../game/enums/NetworkPacket";
@@ -128,6 +129,19 @@ export default class Game {
128129

129130
// send tank list to all players
130131
this.io.emit(NetworkPacket.BOARD_STATE_TANKS, Object.values(this.tanks));
132+
133+
// start measuring of latency
134+
let lastPing = new Date().getTime();
135+
let latency = 0;
136+
const pingFn = debounce(() => {
137+
socket.emit(NetworkPacket.GAME_PING, latency);
138+
lastPing = new Date().getTime();
139+
}, 1000);
140+
socket.on(NetworkPacket.GAME_PONG, () => {
141+
latency = new Date().getTime() - lastPing;
142+
pingFn();
143+
});
144+
pingFn();
131145
} else {
132146
socket.emit(NetworkPacket.GAME_HANDSHAKING, {clientId: null, status: HandshakingStatus.FULL});
133147
}

0 commit comments

Comments
 (0)