简体   繁体   English

在圆形物体上收集垃圾?

[英]Garbage Collection on circular objects?

In my ws node.js server, I have it so that when a client connects, it assigns a "user" object to their websocket object, and inside that user object is a reference back to their websocket object. 在我的ws node.js服务器中,我拥有它,以便客户端连接时,它将“用户”对象分配给其websocket对象,并且在该用户对象内部是对其websocket对象的引用。 This lets me send data to a client when I only know their user object (all game logic only deals in user objects, not websockets), and it lets me get a client's user information when data comes in from their websocket object. 这样,当我仅知道客户端的用户对象(所有游戏逻辑仅处理用户对象,而不处理websocket)时,我便可以将数据发送给客户端,并且当数据来自其websocket对象时,它还可以获取客户端的用户信息。

I've heard that circular objects can cause issues where garbage collection will never clean them up because they have references to each other, so my question is, what do I need to do to make sure that when a client disconnects, their websocket and user objects both get properly removed from memory? 我听说圆形对象可能会导致垃圾回收永远不会清理的问题,因为它们相互引用, 所以我的问题是,当客户端断开连接时,我该怎么办才能确保其websocket和用户两个对象都已正确从内存中删除?

Also, let me know if I'm going about this in completely the wrong way! 另外,让我知道我是否完全以错误的方式进行此操作! :P :P


Edit: Code: 编辑:代码:

function onConnect(client) {
    users.push({connected: true, client: client, name: "", messages: 0});
    client.user = users[users.length - 1];
    send("Please enter a username.", [client.user]);
}

You have to manually remove closed connections from the list. 您必须从列表中手动删除关闭的连接。 Otherwise, garbage collector will not remove them from memory. 否则,垃圾收集器不会将其从内存中删除。

function onConnect(client) {
  users.push({
    connected: true,
    client: client,
    name: "",
    messages: 0
  });
  client.user = users[users.length - 1];
  client.on('close', function(){
    //remove closed connection from the list then let garbage collector does its job.
    users.splice(users.indexOf(client.user), 1);
  });
  send("Please enter a username.", [client.user]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM