Skip to content

Commit

Permalink
feat(TCP & WebSocket severs): Add onConnected and onDisconnected methods
Browse files Browse the repository at this point in the history
  • Loading branch information
nokome committed Oct 23, 2019
1 parent ae2c27e commit f891e53
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
14 changes: 9 additions & 5 deletions src/tcp/TcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@ export class TcpServer extends StreamServer {
})
}

protected onConnection(client: Socket): void {
protected onConnected(client: Socket): void {
this.clients.push(client)
client.on('close', () => {
this.clients.splice(this.clients.indexOf(client), 1)
})
}

protected onDisconnected(client: Socket): void {
this.clients.splice(this.clients.indexOf(client), 1)
}

public async start(executor?: Executor): Promise<void> {
Expand All @@ -48,7 +49,10 @@ export class TcpServer extends StreamServer {
)
})
}))
server.on('connection', client => this.onConnection(client))
server.on('connection', client => {
this.onConnected(client)
client.on('close', () => this.onDisconnected(client))
})

const { host, port } = this.address
return new Promise(resolve => server.listen(port, host, () => resolve()))
Expand Down
5 changes: 3 additions & 2 deletions src/ws/WebSocketServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ export class WebSocketServer extends HttpServer {
socket.on('message', async (message: string) => {
socket.send(await this.receive(message))
})
// Register connection
this.onConnection(connection)
// Register connection and disconnection handler
this.onConnected(connection)
socket.on('close', () => this.onDisconnected(connection))
},
options: {
verifyClient: authorize
Expand Down

0 comments on commit f891e53

Please sign in to comment.