2020-03-21 07:47:42 +00:00
|
|
|
import { EventEmitter } from 'events'
|
|
|
|
|
|
|
|
import { ServerEvent, Keys } from './constants'
|
|
|
|
import { WebSocketDetect } from './websocket_detect'
|
|
|
|
import { WebSocketHandler } from './websocket_handler'
|
|
|
|
import { NettyClient } from './client'
|
2020-03-31 06:53:23 +00:00
|
|
|
import { ServerOptions } from '../socket-io'
|
2020-03-21 07:47:42 +00:00
|
|
|
|
2020-03-24 05:27:11 +00:00
|
|
|
class NettyWebSocketServer extends EventEmitter {
|
2020-03-21 07:47:42 +00:00
|
|
|
private pipeline: any;
|
|
|
|
private allClients: { [key: string]: NettyClient };
|
|
|
|
|
2020-03-24 10:30:50 +00:00
|
|
|
constructor(pipeline: any, options: ServerOptions) {
|
2020-03-24 05:27:11 +00:00
|
|
|
super()
|
2020-03-21 07:47:42 +00:00
|
|
|
this.allClients = {};
|
|
|
|
this.pipeline = pipeline;
|
2020-03-22 16:58:53 +00:00
|
|
|
let connectEvent = options.event;
|
2020-03-24 10:30:50 +00:00
|
|
|
try { this.pipeline.remove(Keys.Detect) } catch (error) { }
|
2020-03-21 07:47:42 +00:00
|
|
|
this.pipeline.addFirst(Keys.Detect, new WebSocketDetect(connectEvent).getHandler())
|
|
|
|
connectEvent.on(ServerEvent.detect, (ctx, channel) => {
|
2020-03-22 16:58:53 +00:00
|
|
|
channel.pipeline().addFirst(Keys.Handler, new WebSocketHandler(options).getHandler())
|
2020-03-21 07:47:42 +00:00
|
|
|
ctx.fireChannelRead(channel)
|
|
|
|
})
|
|
|
|
connectEvent.on(ServerEvent.connect, (ctx) => {
|
2020-04-07 05:31:20 +00:00
|
|
|
console.log('NettyWebSocketServer ServerEvent.connect', ctx, ctx.channel().id(), ctx.channel().class.name)
|
2020-03-22 16:58:53 +00:00
|
|
|
let nettyClient = new NettyClient(this, ctx.channel());
|
2020-03-21 07:47:42 +00:00
|
|
|
this.allClients[nettyClient.id] = nettyClient;
|
2020-03-24 05:27:11 +00:00
|
|
|
this.emit(ServerEvent.connect, nettyClient);
|
2020-03-21 07:47:42 +00:00
|
|
|
})
|
|
|
|
connectEvent.on(ServerEvent.message, (ctx, msg) => {
|
2020-03-24 10:30:50 +00:00
|
|
|
this.emit(ServerEvent.message, this.allClients[ctx.channel().id()], msg.text())
|
|
|
|
})
|
|
|
|
connectEvent.on(ServerEvent.error, (ctx, cause) => {
|
|
|
|
this.emit(ServerEvent.error, this.allClients[ctx.channel().id()], cause)
|
2020-03-21 07:47:42 +00:00
|
|
|
})
|
|
|
|
}
|
2020-03-24 05:27:11 +00:00
|
|
|
close() {
|
2020-03-21 07:47:42 +00:00
|
|
|
if (this.pipeline.names().contains(Keys.Detect)) {
|
|
|
|
this.pipeline.remove(Keys.Detect)
|
|
|
|
}
|
2020-03-24 05:27:11 +00:00
|
|
|
Object.values(this.allClients).forEach(client => client.close())
|
2020-03-21 07:47:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
NettyWebSocketServer,
|
|
|
|
ServerEvent,
|
|
|
|
NettyClient
|
|
|
|
};
|