javascript 在断开 socket.io 上删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9918203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:13:27  来源:igfitidea点击:

Remove objects on disconnect socket.io

javascriptnode.jssocket.io

提问by dzm

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

我正在使用 Nodejs 和 Socket.io。当客户端连接时,会创建新的 JavaScript 对象。

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!

谢谢!

回答by Mohamed Mansour

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 disconnectevent listener:

一旦用户断开连接,您应该通过绑定到disconnect事件侦听器进行清理:

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

  socket.on('disconnect', function() {
    delete clients[socket.id];
  });
});