[英]Why does socket.on() gets called multiple times
I am making a small game with socket.io. 我正在用socket.io做一个小游戏。
Server side code(app.js) is running on Node... 服务器端代码(app.js)正在Node上运行...
Client side code is in game.js 客户端代码在game.js中
Inside app.js, I have this 在app.js里面,我有这个
app.get("/playgame", (req, res) => {
res.sendFile(__dirname + "/public/game.html");
});
The Game set up: Player-1 will be the challenger by default. 游戏设置:默认情况下,Player-1将成为挑战者。 Player-2 accepts the challenge.
Player-2接受挑战。
io.on('connection', (socket) => {
socket.on('createChallenge', function(data) {
let obj = {
id: getroomID(),
players: [{ sock: socket.id, name: data.player1.toLowerCase() }]
};
if (io.sockets.mygameChallenges) {
io.sockets.mygameChallenges.push(obj);
} else {
let rooms = [];
rooms.push(obj);
io.sockets.mygameChallenges= rooms;
}
socket.emit("chalengecreated", { player: data.player1, id: obj.id });
});
Everything works fine until here.. 一切正常,直到这里..
On entering incorrect game id, I am facing this issue 在输入错误的游戏ID时,我正面临着这个问题
1) Player-2 gets alert message for entering incorrect ID (This works perfect) 1)Player-2收到输入错误ID的警告信息(这很完美)
2) if P-2 again enters incorrect game id, this time gets two alert messages. 2)如果P-2再次输入错误的游戏ID,则此时会收到两条警报消息。
3) if Third time on entering incorrect game id, gets 3 alert messages... 3)如果第三次输入错误的游戏ID,则获得3条警报消息...
Here is that piece of code thats getting called multiple times 这是一段被多次调用的代码
Game.js: Game.js:
socket.on('errorID', function(data) {
// this gets called multiple times. Not sure why
if (data.error) {
console.log(data.rooms);
alert(data.error);
} else {
alert(data);
}
});
App.js: App.js:
if (!matched) {
console.log('ID not found'); // This gets called only once as expected.
socket.emit('errorID', { error: "ID not found", rooms: io.sockets.mygameChallenges});
}
I found the cause. 我找到了原因。
socket.on() eventhandle was getting setup each and everytime the player enters an incorrect id and clicks the button. socket.on()eventhandle每次播放器输入错误的ID并单击按钮时都会进行设置。
Solution: I used a boolean so that when the player enters incorrect ID for first time, the on() event is setup. 解决方案:我使用了一个布尔值,以便当玩家第一次输入错误的ID时,会设置on()事件。 From Second time onwards on() will not be setup as the boolean is now false
从第二次起,on()将不会被设置,因为布尔值现在为false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.