我是NodeJS新手,&我想用socket.io創建一個多人遊戲。下面是摘錄:在socket.io中斷開連接後刪除對象
io.on("connection", function(socket){
players.push(socket);
if(players.length === 2){
console.log("2 players connected");
var n = matches.length;
matches[n] = new Match(poll,matches,n).init();
}
所以,這很簡單,當有2名球員(2個插槽)在陣的球員,我創建數組中的玩家一個新的匹配,並將其存儲在比賽陣列,但我的顧慮來到了這裏,我需要當一個玩家(或他們兩個)斷開Match時刪除對象Match,我知道JavaScript使用垃圾回收,但我做了以下測試,我設法從數組匹配,但Match仍然存在,我猜想這是因爲兩個玩家的連接都存在,但是如果兩個玩家斷開連接,我可以確定Match對象沒有存儲在內存中的某個地方?
這是比賽的外觀現在:
function Match(players, matches, id) {
this.playerOne = players[0];
this.playerTwo = players[1];
this.board = [["0","0","0"],["0","0","0"],["0","0","0"]];
this.id = id;
this.matches = matches;
}
Match.prototype.init = function(){
console.log("new game!");
var that = this;
this.playerOne.on("moved", function(c){
console.log("player one moved")
that.playerTwo.emit("opponent-moved",c);
});
this.playerTwo.on("moved", function(c){
console.log("player two moved")
that.playerOne.emit("opponent-moved",c);
});
this.playerOne.on("disconnect",function(){
console.log("Player one disconnected");
// that.io.emit("delete", that.id);
that.matches.splice(that.id,1);
});
}
所有對匹配的引用都必須刪除才能獲取垃圾回收(這也不會立即發生)。 'init'看起來像什麼? –
@CoryDanielson在init中,我爲兩個玩家添加了幾個偵聽器。 –
您必須解除兩個玩家的偵聽器綁定並從陣列中刪除匹配。然後它會被清理乾淨。 Match是否有一個緊密的方法來取消init的作用? –