chat-app/build/WebSocketHandler.js

59 lines
2.3 KiB
JavaScript

"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
exports.WebSocketHandler = void 0;
var WebSocket = require("ws");
var events_1 = require("events");
var Logger_1 = require("./Logger");
var chalk = require("chalk");
var Client_1 = require("./Client");
var WebSocketHandler = /** @class */ (function (_super) {
__extends(WebSocketHandler, _super);
function WebSocketHandler(server) {
var _this = _super.call(this) || this;
_this.server = server;
_this.bindEventListeners();
_this.logger = new Logger_1.Logger('WebSocketHandler', chalk.yellow);
_this.clients = new Map();
_this.emit('startwss');
_this.emit('ready');
return _this;
}
WebSocketHandler.prototype.bindEventListeners = function () {
var _this = this;
this.on('ready', function () {
_this.logger.log('WebSocket handler ready.');
});
this.on('startwss', function () {
_this.logger.log('Starting WebSocket server...');
var nextClientID = 0;
_this.wss = new WebSocket.Server({
noServer: true
});
_this.wss.on('connection', function (ws, req) {
_this.clients.set(nextClientID, new Client_1.Client(nextClientID, ws, _this.server));
nextClientID++;
});
_this.wss.on('close', function () {
_this.logger.warn('WebSocket server closed.');
});
});
};
return WebSocketHandler;
}(events_1.EventEmitter));
exports.WebSocketHandler = WebSocketHandler;