From 6f8659083c4bb068e7c91b992baae73fc828c1b1 Mon Sep 17 00:00:00 2001 From: AmirHossein Mahmoodi Date: Sat, 10 May 2025 08:55:19 +0330 Subject: [PATCH] add online clients event --- src/socket/socket.gateway.ts | 23 +++++++++++++++++++++-- src/socket/socket.service.ts | 13 +++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/socket/socket.gateway.ts b/src/socket/socket.gateway.ts index 32ea9e4..2639cb5 100644 --- a/src/socket/socket.gateway.ts +++ b/src/socket/socket.gateway.ts @@ -21,18 +21,29 @@ export class SocketGateway implements OnGatewayConnection { constructor(private socketService: SocketService) {} async handleConnection(client: Socket) { + const clientId = client.handshake.auth.token; + await this.socketService.clientConnection({ - client_id: client.handshake.auth.token, + client_id: JSON.stringify(clientId), socket_id: client.id, event: 'connected', }); + + this.socketService.setOnlineClient(clientId, client.id); + + this.broadcastOnlineClients(); + client.on('disconnect', async (reason) => { await this.socketService.clientConnection({ - client_id: client.handshake.auth.token, + client_id: JSON.stringify(clientId), socket_id: client.id, event: 'disconnected', description: reason, }); + + this.socketService.removeOnlineClient(clientId); + + this.broadcastOnlineClients(); }); } @@ -55,6 +66,14 @@ export class SocketGateway implements OnGatewayConnection { return result; } + broadcastOnlineClients() { + const onlineClients = this.socketService.getOnlineClients(); + + this.server.emit('onlineClientsUpdated', { + clients: onlineClients, + }); + } + getConnectedClients(clientsId: string[]): Socket[] { const socketsMap = this.server?.sockets?.sockets; if (!socketsMap) return []; diff --git a/src/socket/socket.service.ts b/src/socket/socket.service.ts index d6c646a..187ac75 100644 --- a/src/socket/socket.service.ts +++ b/src/socket/socket.service.ts @@ -10,6 +10,7 @@ import { SocketConnection } from './socket.entity'; @Injectable() export class SocketService { private readonly logger = new Logger(SocketService.name); + private readonly onlineClients = new Map(); constructor( @InjectRepository(SocketConnection) @@ -75,4 +76,16 @@ export class SocketService { message: 'Success in sending to all clients!', }; } + + setOnlineClient(clientId: string, socketId: string) { + this.onlineClients.set(clientId, socketId); + } + + removeOnlineClient(clientId: string) { + this.onlineClients.delete(clientId); + } + + getOnlineClients(): string[] { + return [...this.onlineClients.keys()]; + } }