19

I'm using Nodejs and Socket.io. When the client connects, new JavaScript objects are created.

Do these objects just linger forever? Should they be deleted or removed when the client disconnects? Is it even possible to remove an object? I know delete won't work...

Thanks - I guess this is more of a general question and any suggestions would be really helpful.

Thanks!

dzm
  • 22,844
  • 47
  • 146
  • 226

2 Answers2

28

If you don't cleanup, then yes, they will stay there forever since I assume you are making them global.

You should cleanup once a user disconnects by binding to the disconnect event listener:

var clients = {}
sockets.on('connection', function(socket) {
  clients[socket.id] = socket;

  socket.on('disconnect', function() {
    delete clients[socket.id];
  });
});
Christian
  • 27,509
  • 17
  • 111
  • 155
Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
  • 1
    Great, thank you! I assume I can use the same method for 'clients' to keep track of other objects as well? There are several other objects outside of the 'socket' functionality that are created. – dzm Mar 29 '12 at 03:46
  • 1
    jup! What some people do, they add the objects inside the "socket" variable, and it gets destroyed automatically. `socket.data = "foo"` and then the clients just has a id to that socket. – Mohamed Mansour Mar 29 '12 at 04:27
  • 6
    I don't know why, but `delete clients[socket.id];` sometimes just doesn't work. From my research it seems a socket.io issue... – Christian Sep 17 '12 at 14:04
  • 1
    @ christian yup i too had that problem....grrrrr ....i finally used 'sync disconnect on unload' : true in io.connect (client side) and somehow it worked – Nav Jun 07 '13 at 05:50
  • `delete` is not allowed in `strict mode` is there another way to achieve this? – Vivek Molkar Mar 24 '17 at 14:32
  • What if I don't explicitly store the sockets anywhere? Does it still need to be cleaned up? I am wondering if I should do something like `io.remove(socket)`. – Nimish David Mathew Mar 16 '20 at 08:18
0
   socket.on('disconnect', disc => {
    console.log("disconnect");
    console.log(socket.id);
    console.log(rects);
    console.log(rects.indexOf(id));
      let index = rects.indexOf(id);
      rects.splice(index, 1);
      socket.broadcast.emit("discon", id);  
   });