throttle 'tilts' from the server
This commit is contained in:
25
server.ts
25
server.ts
@@ -4,6 +4,8 @@ import { Server as SocketIOServer, type Socket } from 'socket.io';
|
||||
|
||||
import GameStore from '@/lib/GameStore';
|
||||
import omit from '@/tools/omit';
|
||||
|
||||
import { thirtyFPS } from '@/constants/time';
|
||||
import type { ClientUpdate, GameUpdate, Tilt } from '@/types';
|
||||
|
||||
const dev = process.env.NODE_ENV !== 'production';
|
||||
@@ -15,6 +17,8 @@ const handler = app.getRequestHandler();
|
||||
|
||||
const gameStore = new GameStore();
|
||||
|
||||
const timedReleases = {};
|
||||
|
||||
app.prepare().then(() => {
|
||||
const httpServer = createServer(handler);
|
||||
|
||||
@@ -25,6 +29,25 @@ app.prepare().then(() => {
|
||||
io.to(gameUpdate.spectatorID).emit(event, omit(gameUpdate, 'dmID'));
|
||||
};
|
||||
|
||||
const timedRelease = (event: string, gameUpdate: GameUpdate, threshold: number) => {
|
||||
const now = Date.now();
|
||||
const lastEvent = timedReleases[event];
|
||||
|
||||
if (lastEvent?.embargo >= now) {
|
||||
clearTimeout(lastEvent.to);
|
||||
const embargo = lastEvent.embargo - now;
|
||||
|
||||
const to = setTimeout(() => {
|
||||
broadcast(event, gameUpdate);
|
||||
}, embargo);
|
||||
|
||||
timedReleases[event] = { embargo, to };
|
||||
} else {
|
||||
broadcast(event, gameUpdate);
|
||||
timedReleases[event] = { embargo: now + threshold };
|
||||
}
|
||||
};
|
||||
|
||||
io.on('connection', (socket: Socket) => {
|
||||
//console.log(Date.now(), `Client connected: ${socket.id}`);
|
||||
|
||||
@@ -122,7 +145,7 @@ app.prepare().then(() => {
|
||||
socket.on('tilt', ({ cardIndex, tilt }: { cardIndex: number; tilt: Tilt }) => {
|
||||
try {
|
||||
const gameState = gameStore.tilt(socket.id, cardIndex, tilt);
|
||||
broadcast('game-update', gameState);
|
||||
timedRelease('game-update', gameState, thirtyFPS);
|
||||
} catch (e) {
|
||||
const error = e instanceof Error ? e.message : e;
|
||||
console.error(Date.now(), 'Error[tilt]', error);
|
||||
|
||||
Reference in New Issue
Block a user