Socket.io and Express on NodeJS emmit looping

11 viewsexpressnode.jssocket.io
0

I am trying to learn socket.io and for my latest app. I am trying to create a stickman multiplayer game. After I created my stickman class for each time a new user entered the game it will trigger the class. In my server.js

const express = require("express"); const http = require('http'); const socketIO = require('socket.io'); const path = require("path"); const Game = require('./server/game.js');

const app = express(); const server = http.createServer(app); const io
= socketIO(server, { pingInterval: 2000, pingTimeout: 5000 }); const game = new Game();

// Serve static files app.use(express.static(path.join(__dirname, "static"))); app.use(express.static(path.join(__dirname, "server")));

app.set("view engine", "ejs");

app.get("/", function(request, response) {
    response.render("index"); });

const players = {};

io.on('connection', function(socket) {
    console.log(`user ${socket.id} is connected`)
    if (!players[socket.id]) {
        players[socket.id] = {
            x: 500 * Math.random(),
            y: 500 * Math.random()
        };
    }

    console.log(players);
    io.emit('updatePlayers', players);

    socket.on('disconnect', (reason) => {
        console.log(`user ${socket.id} is removed`);
        delete players[socket.id];
        io.emit('disconnectPlayers', players);
    }); });

app.get("/", function(request, response) {
    response.render("index"); });

const PORT = process.env.PORT || 8000; server.listen(PORT, function() {
    console.log(`Server is running on port ${PORT}`); });

Each time a new user enters the game, its ID will be pushed to an object variable called players with x and y coordinates for random spawning. Then after that, it will be passed down to io.emit('updatePlayers', players); At first, I tried to use the same name updatePlayers but it looped, and even I created another io.emit name thinking it was maybe disrupting the flow so I am going to create new emit called io.emit('disconnectPlayers', players);

Here is my client-side js called client.js

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d');

let player = new Player(200, 500);
const players = {};
const socket = io();

socket.on('updatePlayers', function(backEndPlayers) {
    for (const id in backEndPlayers) {
        const backEndplayer = backEndPlayers[id]
        if (!players[id]) {
            players[id] = new Player(backEndplayer.x, backEndplayer.y)
        }
    }
});

socket.on('disconnectPlayers', function(backEndPlayers) {
    for (const id in players) {
        if (!backEndPlayers[id]) {
            delete players[id]
        }
    }
});

function animate() {
    requestAnimationFrame(animate);

    for (const id in players) {
        const player = players[id];
        player.createPlayer()
        player.updateSpriteSheet();
    }
}

animate();

Vise-versa, after the players object is passed on to the client side, another object variable called players (the same variable name) will get all of the information. I would like to understand the cause of the socket.id looping even I didn’t open new browser or refreshed it.