N
N
newaitix2017-02-11 12:40:00
JavaScript
newaitix, 2017-02-11 12:40:00

How to delete a connection if the user has moved to another page?

var clients={};
exports.subscribe=function(req,res,id){
  if(typeof id=='number'&&id>=0){
    if(typeof clients[id]=='undefined')
      clients[id]=[];
    var cl=clients[id];
  }
  cl.push(res);
  res.on('close',function(){
    console.log('disconnect chat №',id);
    cl.splice(cl.indexOf(res),1);
  });
};
exports.publish=function(message){
  var id=message['id'];
  clients[id].forEach(function(res){
    res.end('{"message":"'+message['body']+'"}');
  });
  clients[id]=[];
};

When a user subscribes to events, it is added to the clients[room_id] array.
Immediately res.on('close',function(){..., if the connection is closed by the client, then it is removed from the array.
close fires if the user has refreshed the page or closed the tab/browser. And if the user has moved to another page, then close will not work. How to be in this situation?
Including I do not understand how to distinguish one connection from another.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2017-02-11
@newaitix

to hang up in window.onbeforeunload the code sending some unsubscribe?
Or double the traffic - expect a mandatory response from the client to each message from the server - at the same time it will help to estimate the speed of communication with this client very roughly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question