feat: optimize websocket

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2020-11-13 09:40:47 +08:00
parent a76f9e8b50
commit f86e1a8c94
10 changed files with 195 additions and 126 deletions

View File

@@ -9,14 +9,14 @@ import { WebSocketDetect } from './websocket_detect'
import { WebSocketHandler } from './websocket_handler'
class NettyWebSocketServer extends EventEmitter {
private pipeline: any;
private allClients: { [key: string]: NettyClient };
private pipeline: any
private clients: Map<string, NettyClient>
constructor(pipeline: any, options: ServerOptions) {
super()
this.allClients = {};
this.pipeline = pipeline;
let connectEvent = options.event;
this.clients = new Map()
this.pipeline = pipeline
let connectEvent = options.event
try { this.pipeline.remove(Keys.Detect) } catch (error) { }
this.pipeline.addFirst(Keys.Detect, new WebSocketDetect(connectEvent).getHandler())
connectEvent.on(ServerEvent.detect, (ctx, channel) => {
@@ -24,22 +24,42 @@ class NettyWebSocketServer extends EventEmitter {
ctx.fireChannelRead(channel)
})
connectEvent.on(ServerEvent.connect, (ctx) => {
let cid = ctx?.channel().id() + ''
let nettyClient = new NettyClient(this, ctx.channel())
this.allClients[nettyClient.id] = nettyClient
this.clients.set(cid, nettyClient)
this.emit(ServerEvent.connect, nettyClient)
})
connectEvent.on(ServerEvent.message, (ctx, msg) => {
this.emit(ServerEvent.message, this.allClients[ctx.channel().id()], msg.text())
let cid = ctx?.channel().id() + ''
if (this.clients.has(cid)) {
this.emit(ServerEvent.message, this.clients.get(cid), msg.text())
} else {
console.error(`unknow client ${ctx} reciver message ${msg.text()}`)
}
})
connectEvent.on(ServerEvent.disconnect, (ctx, cause) => {
let cid = ctx?.channel().id() + ''
if (this.clients.has(cid)) {
this.emit(ServerEvent.disconnect, this.clients.get(cid), cause)
} else {
console.error(`unknow client ${ctx} disconnect cause ${cause}`)
}
})
connectEvent.on(ServerEvent.error, (ctx, cause) => {
this.emit(ServerEvent.error, this.allClients[ctx.channel().id()], cause)
let cid = ctx?.channel().id() + ''
if (this.clients.has(cid)) {
this.emit(ServerEvent.error, this.clients.get(cid), cause)
} else {
console.error(`unknow client ${ctx} cause error ${cause}`)
console.ex(cause)
}
})
}
close() {
if (this.pipeline.names().contains(Keys.Detect)) {
this.pipeline.remove(Keys.Detect)
}
Object.values(this.allClients).forEach(client => client.close())
this.clients.forEach(client => client.close())
}
}