| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import {
- Socket,
- } from "socket.io";
- import {
- Command,
- User,
- Deserialize,
- Server,
- Conflict,
- TransformUtils,
- } from "../internal";
- export class ServerSocket extends Server {
- protected _roomId: string;
- protected _users: Array<User>;
- protected _source: unknown;
- public constructor(conflict: Conflict)
- public constructor(conflict: Conflict, source: unknown)
- public constructor(...parameter: any) {
- if (TransformUtils.hasLength(parameter, 1)) {
- const conflict = parameter[0];
- super(conflict);
- this._users = [];
- this._roomId = 'empty';
- this._source = null;
- return;
- }
- if (TransformUtils.hasLength(parameter, 2)) {
- const conflict = parameter[0];
- const source = parameter[1];
- super(conflict);
- this._users = [];
- this._roomId = 'empty';
- this._source = source;
- }
- }
- public onCommand(client: Socket, revision: number, command: Command.Serialize): void {
- const deserialize = Deserialize.getInstance().formObject(command);
- const userId = client.id;
- this.receiveCommand(revision, deserialize);
- client.emit('ack');
- client.broadcast.in(this._roomId).emit('command', userId, deserialize.toJSON());
- }
- public onDisconnect(client: Socket): void {
- console.log('Disconnect');
- }
- public addClient(client: Socket): void {
- client.join(this._roomId);
- client.on('command', (revision: number, command: Command.Serialize) => {
- this.onCommand(client, revision, command);
- });
- client.on('disconnect', () => {
- this.onDisconnect(client);
- });
- client.emit('connected', {
- revision: this.getRevision(),
- clients: this._users,
- roomId: this._roomId,
- source: this._source,
- });
- this.addUsers(client);
- }
- public addUsers(client: Socket): void {
- this._users.push({ id: client.id });
- }
- public receiveCommand(revision: number, command: Command) {
- super.receiveCommand(revision, command);
- command.apply(this._source);
- }
- public getSource<T>(): T {
- return <T> this._source;
- }
- }
|