使用socket.removeAllListeners();
我正在使用快递,socket.io
和socket.io-client
:此服务器与另一个服务器相关联,由匹配制作,即发送游戏停止的信息。
var express = require('express');
var url = require('url');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var matchmaking = require("socket.io-client")('http://localhost:1610');
io.on('connection',function(socket){
var page = 'lobby';
show_page(page);
matchmaking.on('ChangePage',function(value){
//switch lobby to game
show_page(value.Page);
});
function show_page(page){
//The user goes here to login and sends info to the matchmaking server
if(page == 'lobby')
{
//If more than 2 players are waiting , the matchmaking server generate a game server, put the waiting players in it and sends it to this server.
}
//If the player joined a game, he's redirected here
else if(page == 'game')
{
socket.on('PlayerMove',function(value){
// The game Code
})
matchmaking.once('END',function(value){
//The game is ended and the user go back to lobby in the players queue where he will be put in another game
socket.removeAllListeners("PlayerMove");
show_page('lobby');
})
}
}
})
当游戏结束时,用户将加入另一个游戏并将通过(page == 'game')
,在那里他将受到另一个听众的影响。所以第一次,游戏完美地运行,但每次他加入新服务器时,监听器内的代码都会成倍增加。
我发现修复它的唯一方法是使代码不符合我的想法。
socket.on('PlayerMove',function(value){
// code inside
}
socket.removeAllListeners("PlayerMove");
matchmaking.once('END',function(value){
})
我的问题有解决办法吗? 提前致谢
我最终解决了这个问题:这个乘法是因为我忘了删除客户端上的套接字。