简体   繁体   中英

Why does socket.on() gets called multiple times

I am making a small game with socket.io.

Server side code(app.js) is running on Node...

Client side code is in game.js

Inside app.js, I have this

app.get("/playgame", (req, res) => {
    res.sendFile(__dirname + "/public/game.html");

});

The Game set up: Player-1 will be the challenger by default. Player-2 accepts the challenge.

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

1) Player-2 gets alert message for entering incorrect ID (This works perfect)

2) if P-2 again enters incorrect game id, this time gets two alert messages.

3) if Third time on entering incorrect game id, gets 3 alert messages...

Here is that piece of code thats getting called multiple times

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:

 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.

Solution: I used a boolean so that when the player enters incorrect ID for first time, the on() event is setup. From Second time onwards on() will not be setup as the boolean is now false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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