forked from hpi-sam/digital-fuesim-manv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.ts
54 lines (46 loc) · 1.71 KB
/
websocket.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { createServer } from 'node:http';
import type * as core from 'express-serve-static-core';
import { Server } from 'socket.io';
import { socketIoTransports } from 'digital-fuesim-manv-shared';
import { Config } from '../config';
import type { ExerciseSocket, ExerciseServer } from '../exercise-server';
import { clientMap } from './client-map';
import { ClientWrapper } from './client-wrapper';
import {
registerGetStateHandler,
registerJoinExerciseHandler,
registerProposeActionHandler,
} from './websocket-handler';
export class ExerciseWebsocketServer {
public readonly exerciseServer: ExerciseServer;
public constructor(app: core.Express) {
const server = createServer(app);
this.exerciseServer = new Server(server, {
// TODO: this is only a temporary solution to make this work
cors: {
origin: '*',
},
...socketIoTransports,
});
this.exerciseServer.listen(Config.websocketPort);
this.exerciseServer.on('connection', (socket) => {
this.registerClient(socket);
});
}
private registerClient(client: ExerciseSocket): void {
// Add client
clientMap.set(client, new ClientWrapper(client));
// register handlers
registerGetStateHandler(this.exerciseServer, client);
registerProposeActionHandler(this.exerciseServer, client);
registerJoinExerciseHandler(this.exerciseServer, client);
// Register disconnect handler
client.on('disconnect', () => {
clientMap.get(client)!.leaveExercise();
clientMap.delete(client);
});
}
public close(): void {
this.exerciseServer.close();
}
}