I am just trying to create a simple app using Socket.io. I am trying to send a notification (technically, emit an event) to all the connected users, if a particular user, User X, has disconnected, that User X has left or has disconnected. Here is my server side code.
io.on('connection', function(socket){
console.log('Connected! ' + socket.id);
socket.on('disconnect', function(){
for(var i=0;i<onlineUsers.length;i++)
{
if(onlineUsers[i].socketId == socket.id)
{
var newMessage = {};
newMessage.socketId = onlineUsers[i].socketId;
newMessage.fullName = onlineUsers[i].fullName;
newMessage.message = newMessage.fullName + " IS DISCONNETED!";
io.emit('newMessage', newMessage);
onlineUsers.splice(i,1);
console.log('splicing id ' + socket.id);
}
}
}
I guess that the code is executing but takes long to emit the disconnection event. I receive the disconnection message about 2 minutes after the client had disconnected. Why does it take so long? What might be the wrong in this code?
I also cannot understand when exactly the client is considered as disconnected. If the app closes, or the browser closes or the internet goes down?
Thanks in advance.
Update: I have a test deployment on Cloud9 and my live deployment is on Azure Cloud. I have realized that Cloud9 works just perfect, this seems like an issue with Azure.
Update 2: Whenever I disconnect/close/refresh my web client, I immediately get the disconnected event emitted by the server. The same does not happen for my mobile client. Why?