smartsocket/ts/smartsocket.classes.smartsocket.ts

68 lines
1.8 KiB
TypeScript
Raw Normal View History

2016-08-07 12:58:20 +00:00
import * as plugins from "./smartsocket.plugins";
import * as helpers from "./smartsocket.helpers";
// classes
import { Objectmap } from "lik";
2016-08-07 13:37:52 +00:00
import {SocketRole} from "./smartsocket.classes.socketrole";
import {SocketFunction} from "./smartsocket.classes.socketfunction";
2016-08-07 12:58:20 +00:00
export interface ISocketObject {
2016-08-07 16:59:39 +00:00
alias?:string;
2016-08-07 12:58:20 +00:00
authenticated: boolean
2016-08-07 16:59:39 +00:00
role?:string,
socket: SocketIO.Socket,
2016-08-07 12:58:20 +00:00
};
export interface ISmartsocketConstructorOptions {
port: number;
2016-08-07 13:37:52 +00:00
};
2016-08-07 12:58:20 +00:00
export class Smartsocket {
2016-08-07 16:59:39 +00:00
options:ISmartsocketConstructorOptions
2016-08-07 12:58:20 +00:00
io: SocketIO.Server;
openSockets = new Objectmap();
2016-08-07 13:37:52 +00:00
registeredRoles = new Objectmap();
2016-08-07 16:59:39 +00:00
constructor(optionsArg: ISmartsocketConstructorOptions) {
this.options = optionsArg;
2016-08-07 12:58:20 +00:00
};
/**
* the standard handler for new socket connections
*/
private _handleSocket(socket) {
let socketObject: ISocketObject = {
socket: socket,
authenticated: false
};
2016-08-07 16:59:39 +00:00
plugins.beautylog.log("Socket connected. Trying to authenticate...")
2016-08-07 12:58:20 +00:00
this.openSockets.add(socketObject);
helpers.authenticateSocket(socketObject)
.then();
}
2016-08-07 16:59:39 +00:00
registerFunctions(socketRoleArg:SocketRole){
2016-08-07 13:37:52 +00:00
this.registeredRoles.add(socketRoleArg);
};
2016-08-07 16:59:39 +00:00
/**
* starts listening to incling sockets:
*/
2016-08-07 12:58:20 +00:00
2016-08-07 16:59:39 +00:00
startServer = () => {
this.io = plugins.socketIo(this.options.port);
this.io.on('connection', (socketArg) => {
this._handleSocket(socketArg);
});
}
2016-08-07 12:58:20 +00:00
closeServer = () => {
this.openSockets.forEach((socketObjectArg: ISocketObject) => {
2016-08-07 16:59:39 +00:00
plugins.beautylog.log(`disconnect socket with >>alias ${socketObjectArg.alias}`);
2016-08-07 12:58:20 +00:00
socketObjectArg.socket.disconnect();
});
this.openSockets.wipe();
2016-08-07 16:59:39 +00:00
this.io.close();
2016-08-07 12:58:20 +00:00
}
}