feat: 优化websocket

Signed-off-by: MiaoWoo <admin@yumc.pw>
backup
MiaoWoo 2021-10-25 15:56:23 +08:00
parent cf9153c134
commit 476d98b9c7
5 changed files with 9 additions and 7 deletions

View File

@ -53,13 +53,11 @@ export class WebSocket extends EventEmitter {
return
}
this.client.on('open', (event) => {
console.debug('client WebSocket call open', this.onopen)
this.onopen?.(event)
manager.add(this)
})
this.client.on('message', (event) => this.onmessage?.(event))
this.client.on('close', (event) => {
console.log('client WebSocket call close', this.onclose)
this.onclose?.(event)
manager.del(this)
})
@ -101,3 +99,4 @@ export class WebSocket extends EventEmitter {
this.removeAllListeners()
}
}
global.setGlobal('WebSocket', WebSocket)

View File

@ -29,7 +29,7 @@ export class WebSocketClientHandler extends WebSocketClientHandlerAdapter {
}
channelInactive(ctx: any) {
console.debug(`${ctx} channelInactive`)
this.client.onclose({ code: 0, reason: 'server connection channel inactive!' })
this.client.onclose({ code: 0, reason: 'client connection channel inactive!' })
}
channelRead0(ctx: any, msg: any) {
console.trace(`${ctx} channelRead0 ${msg}`)
@ -50,7 +50,7 @@ export class WebSocketClientHandler extends WebSocketClientHandlerAdapter {
if (frame instanceof TextWebSocketFrame) {
this.client.onmessage({ data: frame.text() })
} else if (frame instanceof CloseWebSocketFrame) {
this.client.onclose({ code: 0, reason: 'server send CloseWebSocketFrame!' })
this.client.onclose({ code: 0, reason: 'server close connection!' })
}
}
exceptionCaught(ctx: any, cause: Error) {

View File

@ -100,9 +100,11 @@ export class NettyWebSocket extends Transport {
handler.handshakeFuture.addListener(new ChannelFutureListener((future: any) => {
try {
future.sync()
// only trigger onconnect when not have error
this.onconnect({})
} catch (error) {
this.onerror({ error })
// ignore error exceptionCaught from handler
// this.onerror({ error })
}
}))
}))

View File

@ -57,6 +57,8 @@ export abstract class Transport extends EventEmitter {
this.doClose(code, reason)
} catch (error) {
this.onerror({ error })
} finally {
this.removeAllListeners()
}
} else {
console.debug(`${this.id} call close but state is ${this.readyStatus}`)
@ -69,7 +71,6 @@ export abstract class Transport extends EventEmitter {
}
onconnect(event: Event) {
console.debug(`${this.id} call onconnect`)
if (this.readyStatus != WebSocket.OPEN) {
this.readyStatus = WebSocket.OPEN
this.emit('open', event)

View File

@ -200,7 +200,7 @@ export class Client<
* @private
*/
private close(): void {
console.debug(`client ${this.id} clise - reason: forcing transport close`)
console.debug(`client ${this.id} close - reason: forcing transport close`)
if ("open" === this.conn.readyState) {
console.debug("forcing transport close")
this.conn.close()