简体   繁体   中英

NodeJS socket.io socket does not emit

I'm working using socket.io on NodeJS to create bots for MooMoo.io. Everything seems to work fine except the bots will not accept a clan invitation.

Here is the part that is broken:

socket.emit("11", a, 1); // a = player ID

Here's my code:

const io = require("socket.io-client");
var socket = io.connect("http://52.39.43.139:" + (5006) + '', {
    reconnection: false,
    query: "man=1"
});
var n = 0;

function spawn(i) {
    n++;
    if (n >= 10) return null;
    socket = io.connect("http://52.39.43.139:" + (5000 + i % 11) + '', {
        reconnection: false,
        query: "man=1"
    });
    socket.once("connect", () => {
        socket.emit("1", {name: "ME"}); // spawn
        socket.emit("10", "ME"); // request to join clan
    });
}
socket.once("connect", () => {
    socket.emit("1", {
        name: "ME"
    }); // spawn
    socket.emit("8", "ME"); // create clan
    console.log("Clan created");
});

team = [];

var i = 0;
setInterval(() => spawn(i), 3000);
socket.on("an", (a, name) => { // player requests to join clan event
    socket.emit("11", a, 1); // accept invite
    console.log(`${name} successfully joined :)`);
    team.push(a);
    console.log(team);
});
socket.on("ad", (a) => { // player leaves clan event
    for (var c = team.length - 1; c >= 0; c--)
        if (team[c].sid == a) {
            team.splice(c, 1);
            console.log(team[c].name + ' has left');
        }
    console.log(team);
});
socket.on("11", () => { // respawn event
    console.log("I have died, respawning...")
    socket.emit("1", { // spawn event
        name: "ME"
    });
});

According to the part you described as being broke you shouldn't pass extra variables like this:

socket.emit("11", a, 1); // a = player ID

But rather it should look like this;

socket.emit("11", {
   playerID:a,
   otherVariable:1
}); 

Which you can acess in your server code by using:

socket.on('11', function(data){
   console.log(data.playerID);
   console.log(data.otherVariable);
});

If you can provide more detail about other problems your having I can try to help you further, but you only highlighted that that emit didn't work and we don't have your backend code to reference here.

Another note, You shouldn't be passing anything but either a single variable (which the documentation still doesn't link and prefers passing via object) or an object. You also shouldn't be using socket.once in this context as it's not needed in my opinion

Turns out the server limited one connection per port. Fixed by using different ports.

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