feat: export error handle & merge config

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2020-03-24 18:30:50 +08:00
parent 73b9c2f163
commit 49b96b3ac4
7 changed files with 44 additions and 41 deletions

View File

@ -1,6 +1,6 @@
import { EventEmitter } from 'events'
import { NettyWebSocketServer } from '../server'
import { NettyWebSocketServer, NettyClient } from '../server'
import { ServerEvent } from '../server/constants';
import { Namespace } from './namespace';
@ -12,6 +12,17 @@ import { Packet } from './packet';
import { Socket } from './socket';
import { Adapter } from './adapter';
interface ServerOptions extends SocketIO.ServerOptions {
event?: EventEmitter;
root?: string;
}
const defaultOptions: ServerOptions = {
event: new EventEmitter(),
path: '/socket.io',
root: root + '/wwwroot'
}
class Server implements SocketIO.Server {
private nettyServer: NettyWebSocketServer;
private allClients: { [key: string]: Client };
@ -24,15 +35,15 @@ class Server implements SocketIO.Server {
local: SocketIO.Server;
parser = new Parser();
_adapter: Adapter;
options: SocketIO.ServerOptions;
options: ServerOptions;
constructor(pipeline: any, options: SocketIO.ServerOptions) {
constructor(pipeline: any, options: ServerOptions) {
if (!pipeline) { throw new Error('Netty Pipeline can\'t be undefiend!') }
this.allClients = {};
this.nsps = {};
this.sockets = new Namespace('/', this);
this.nsps['/'] = this.sockets;
this.initNettyServer(pipeline, options);
this.initNettyServer(pipeline, Object.assign(defaultOptions, options));
}
checkRequest(req: any, fn: (err: any, success: boolean) => void): void {
@ -144,17 +155,18 @@ class Server implements SocketIO.Server {
};
private initNettyServer(pipeline, options) {
this.nettyServer = new NettyWebSocketServer(pipeline, {
event: new EventEmitter(),
path: options.path
});
this.nettyServer.on(ServerEvent.connect, (nettyClient) => {
this.nettyServer = new NettyWebSocketServer(pipeline, options);
this.nettyServer.on(ServerEvent.connect, (nettyClient: NettyClient) => {
let client = new Client(this, nettyClient);
this.onconnection(client);
})
this.nettyServer.on(ServerEvent.message, (nettyClient, text) => {
this.nettyServer.on(ServerEvent.message, (nettyClient: NettyClient, text) => {
this.processPacket(this.parser.decode(text), this.allClients[nettyClient.id]);
})
this.nettyServer.on(ServerEvent.error, (nettyClient: NettyClient, cause) => {
console.error(`Client ${nettyClient.id} cause error: ` + cause)
console.ex(cause)
})
}
private processPacket(packet: Packet, client: Client) {
@ -193,6 +205,6 @@ class Server implements SocketIO.Server {
export {
Server,
Socket,
Server as SocketIOServer,
Client as SocketIOClient
Client,
ServerOptions
}