ServerSocket.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import {
  2. Socket,
  3. } from "socket.io";
  4. import {
  5. Command,
  6. User,
  7. Deserialize,
  8. Server,
  9. Conflict,
  10. TransformUtils,
  11. } from "../internal";
  12. export class ServerSocket extends Server {
  13. protected _roomId: string;
  14. protected _users: Array<User>;
  15. protected _source: unknown;
  16. public constructor(conflict: Conflict)
  17. public constructor(conflict: Conflict, source: unknown)
  18. public constructor(...parameter: any) {
  19. if (TransformUtils.hasLength(parameter, 1)) {
  20. const conflict = parameter[0];
  21. super(conflict);
  22. this._users = [];
  23. this._roomId = 'empty';
  24. this._source = null;
  25. return;
  26. }
  27. if (TransformUtils.hasLength(parameter, 2)) {
  28. const conflict = parameter[0];
  29. const source = parameter[1];
  30. super(conflict);
  31. this._users = [];
  32. this._roomId = 'empty';
  33. this._source = source;
  34. }
  35. }
  36. public onCommand(client: Socket, revision: number, command: Command.Serialize): void {
  37. const deserialize = Deserialize.getInstance().formObject(command);
  38. const userId = client.id;
  39. this.receiveCommand(revision, deserialize);
  40. client.emit('ack');
  41. client.broadcast.in(this._roomId).emit('command', userId, deserialize.toJSON());
  42. }
  43. public onDisconnect(client: Socket): void {
  44. console.log('Disconnect');
  45. }
  46. public addClient(client: Socket): void {
  47. client.join(this._roomId);
  48. client.on('command', (revision: number, command: Command.Serialize) => {
  49. this.onCommand(client, revision, command);
  50. });
  51. client.on('disconnect', () => {
  52. this.onDisconnect(client);
  53. });
  54. client.emit('connected', {
  55. revision: this.getRevision(),
  56. clients: this._users,
  57. roomId: this._roomId,
  58. source: this._source,
  59. });
  60. this.addUsers(client);
  61. }
  62. public addUsers(client: Socket): void {
  63. this._users.push({ id: client.id });
  64. }
  65. public receiveCommand(revision: number, command: Command) {
  66. super.receiveCommand(revision, command);
  67. command.apply(this._source);
  68. }
  69. public getSource<T>(): T {
  70. return <T> this._source;
  71. }
  72. }