2020-03-21 07:47:42 +00:00
|
|
|
import { EventEmitter } from 'events'
|
|
|
|
import { Parser } from './parser'
|
|
|
|
import { Packet } from './packet';
|
|
|
|
import { PacketTypes, SubPacketTypes } from './types';
|
|
|
|
import { ServerEvent, NettyClient } from '../server';
|
|
|
|
import { SocketIO } from './interfaces'
|
|
|
|
|
|
|
|
const parser = new Parser();
|
|
|
|
|
2020-03-22 16:58:53 +00:00
|
|
|
export class Client extends EventEmitter implements SocketIO.Client {
|
2020-03-21 07:47:42 +00:00
|
|
|
private nettyClient: NettyClient;
|
2020-03-22 16:58:53 +00:00
|
|
|
private event: EventEmitter;
|
2020-03-21 07:47:42 +00:00
|
|
|
private _id: string;
|
|
|
|
|
|
|
|
server: SocketIO.Server;
|
|
|
|
conn: SocketIO.EngineSocket;
|
|
|
|
request: any;
|
|
|
|
sockets: { [id: string]: SocketIO.Socket; };
|
|
|
|
nsps: { [nsp: string]: SocketIO.Socket; };
|
|
|
|
|
2020-03-22 16:58:53 +00:00
|
|
|
constructor(server: SocketIO.Server, nettyClient: NettyClient) {
|
|
|
|
super();
|
|
|
|
this.server = server;
|
|
|
|
this.event = new EventEmitter();
|
|
|
|
this.conn = nettyClient;
|
2020-03-21 07:47:42 +00:00
|
|
|
this.nettyClient = nettyClient;
|
|
|
|
this._id = this.nettyClient.id;
|
|
|
|
}
|
|
|
|
get id() {
|
|
|
|
return this._id;
|
|
|
|
}
|
2020-03-22 16:58:53 +00:00
|
|
|
on(event: string, callback: (...args: any[]) => void) {
|
|
|
|
this.event.on(event, callback);
|
|
|
|
return this
|
2020-03-21 07:47:42 +00:00
|
|
|
}
|
2020-03-22 16:58:53 +00:00
|
|
|
emit(event: string, ...args: any[]): boolean {
|
2020-03-21 07:47:42 +00:00
|
|
|
this.packet({
|
|
|
|
type: PacketTypes.MESSAGE,
|
|
|
|
sub_type: SubPacketTypes.EVENT,
|
|
|
|
name: event,
|
2020-03-22 16:58:53 +00:00
|
|
|
data: args[0]
|
2020-03-21 07:47:42 +00:00
|
|
|
})
|
2020-03-22 16:58:53 +00:00
|
|
|
return true;
|
2020-03-21 07:47:42 +00:00
|
|
|
}
|
|
|
|
send(data: any) {
|
|
|
|
this.emit("message", data);
|
|
|
|
}
|
2020-03-22 16:58:53 +00:00
|
|
|
process(packet: Packet) {
|
|
|
|
this.event.emit(packet.name, packet.data);
|
|
|
|
}
|
2020-03-21 07:47:42 +00:00
|
|
|
packet(packet: Packet) {
|
|
|
|
this.nettyClient.send(parser.encode(packet))
|
|
|
|
}
|
|
|
|
}
|