add online clients event

This commit is contained in:
AmirHossein Mahmoodi
2025-05-10 08:55:19 +03:30
parent 63fa018851
commit 6f8659083c
2 changed files with 34 additions and 2 deletions

View File

@@ -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 [];

View File

@@ -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<string, string>();
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()];
}
}