0
//Server Functions
var socketArray = [];
var socketRcon = [];
for (var i = 0; i < serversConfig.serversArray.length; i++) {
    socketArray[i] = new Socket;
    socketArray[i].setEncoding("utf8");
    socketArray[i].setNoDelay();
    socketArray[i].setTimeout(1000);
    socketArray[i].connect(serversConfig.serversArray[i].port, serversConfig.serversArray[i].ip);
    socketRcon[i] = serversConfig.serversArray[i].rcon;
    socketArray[i].on("connect", function() {
        this.write(socketRcon[i] + "\n", "utf8");
        console.log("CONNECTED TO THE SERVER...");
    });
    socketArray[i].on("data", function(data) {
        console.log(data);
    });
    socketArray[i].on("error", function(err) {
        console.log("ERROR:" + err);
    });

    socketArray[i].on("close", function(err) {
        console.log("CLOSED:" + err);
    });
};

This is the code I have now to connect to multiple servers from a config file, and I need that each time the socket connects, I need to send a password to it. But 'socketRcon[i]' is undefined, why is that happening and how do i fix it?

0

2 Answers 2

2

Because by the time that code is run, i is equal to serversConfig.serversArray.length, meaning socketRcon[i] is undefined.

Anchor your value:

for( var i=0; i<l; i++) (function(i) {
    // do stuff here
})(i);
Sign up to request clarification or add additional context in comments.

2 Comments

I tried with: pastebin.com/LBkBRY5g , but apparently the loop didn't execute.
See jslinterrors.com/dont-make-functions-within-a-loop for the reason for having an immediately invoked function expression (IIFE) in the loop and another option that is, in my opinion, more readable.
1

You could also just do:

serversConfig.serversArray.forEach(function(srvconfig) {
  var sock = new Socket();
  sock.setEncoding("utf8");
  sock.setNoDelay();
  sock.setTimeout(1000);

  socketArray.push(sock);
  socketRcon.push(srvconfig.rcon);

  sock.on("connect", function() {
    this.write(srvconfig.rcon + "\n", "utf8");
    console.log("CONNECTED TO THE SERVER...");
  });
  sock.on("data", function(data) {
    console.log(data);
  });
  sock.on("error", function(err) {
    console.log("ERROR:" + err);
  });
  sock.on("close", function(err) {
    console.log("CLOSED:" + err);
  });

  sock.connect(srvconfig.port, srvconfig.ip);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.