Reputation: 1
I have trouble to display the correct amount of online users. So When the user connect the count increase and decrease if disconnect but the problem is when i refresh the page the count still increasing i use angular as frontend and nodejs as backend please i need help to resolve this problem my code ServerSide is
var numberOfOnlineUsers = 0;
io.on('connection', function(socket) {
socket.on('join', function(data){
//joining
numberOfOnlineUsers++;
socket.emit('numberOfOnlineUsers',numberOfOnlineUsers); console.log('Hey, welcome! '+data.username);
socket.broadcast.emit('new user joined',numberOfOnlineUsers );console.log(numberOfOnlineUsers+ ' Users connected!');
});
socket.on('leave', function(data){
numberOfOnlineUsers--;
socket.broadcast.emit('user left',numberOfOnlineUsers);console.log(numberOfOnlineUsers+ ' Users connected!');
});
socket.on('demande',function(data){
socket.broadcast.emit('new demande', {demandeur:data.demandeur, demande:data.demande,datedem:data.datedem});
})
});
and Client Side is:
public ngOnInit(): void {
this.socket.on('new user joined', (numberOfOnlineUsers) => {
this.numberOfOnlineUsers = numberOfOnlineUsers;
console.log(this.numberOfOnlineUsers);
});
this.socket.on('user left', (numberOfOnlineUsers) => {
this.numberOfOnlineUsers = numberOfOnlineUsers;
console.log(this.numberOfOnlineUsers);
});
}
Upvotes: 0
Views: 414
Reputation: 1
My problem is when i reload the page the count of online users increment so i didn't have the real count of the users you understand the issue?
Upvotes: 0
Reputation: 1083
You should subscribe to socket.on('disconnect')
The logic on disconnect event at server side is fired when the socket disconnects due to any reason.
So the code should look like :-
io.on('connection', function(socket) {
.
.
.
socket.on('disconnect', (reason) => {
console.log('Socket disconnected');
});
});
Upvotes: 1