Server.ts 881 Bytes
import express from "express";
import socketIo, { Server as IoServer } from "socket.io";
import { createServer } from "http";
import { RoomManager } from "./room/RoomManager";
import { Connection } from "./connection/Connection";
import { SocketIoWrapper } from "./connection/SocketWrapper";

export class Server {
  public readonly port: number;
  private readonly io: IoServer;

  constructor(port: number) {
    this.port = port;

    const app = express();
    const server = createServer(app);
    this.io = new socketIo.Server(server, {
      cors: {
        origin: "*",
      },
    });

    const roomManager = new RoomManager();

    this.io.on("connection", (socket) => {
      new Connection(new SocketIoWrapper(socket), roomManager);
    });

    server.listen(port, () => console.log(`Listening on ${port}`));
  }

  public close(): void {
    this.io.close();
  }
}