Ad

Input Variable For Connecting To A Specified Socket.io Server

- 1 answer

So I am making an application based off of Socket.io and I am working on my app starting up and asking for a server ip which to connect to as a input variable but I can't seem to figure out how to get it to work. Here's the code:

const chalk = require('chalk').constructor({ enabled: true, level: 3 });;

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

    rl.question(`Please type in Server CURL/IP\n\n `, (serverip) => {
    id = serverip;
    var socket = io(serverip);

    });

var id = "";
var buffer = "";


function chat(){
    rl.question(chalk.magenta("» "), (answer) => {
        buffer = `${chalk.cyan(id)} : ${chalk.blue(answer)}`;
        socket.emit("message", buffer);
        chat();
    });
}

socket.on('connect', () => {

    rl.question(`What is your name?\n\n `, (answer) => {
            socket.emit("message", `${chalk.green(answer)} has joined the chat`);
            id = answer;
            chat();

    });

    socket.on('msg', function(data){
        if(buffer!=data){
            console.log("\n" + data);
            chat();
        }
    });

})

If anyone could help that'd be amazing

Ad

Answer

You're hitting the asynchronous nature of Javascript here. readline.question() returns immediately. When your user finishes answering its question it calls its callback. So, the second of your two var socket = io() lines, the one mentioning server, runs before server is defined.

You must do more work in the callback from readline.question() and less work at your outer level.

Edit I'll try to point you in the right direction. Still, you really do need to read up on Javascript and how callbacks are totally vital to its flow of control.

This is not, repeat not, debugged.

rl.question(`Please type in Server CURL/IP\n\n `, (serverip) => {
  /* only in the this callback function you have access to socket */
  var socket = io(serverip);

  /* use socket here to set up your operations. */
  socket.on('connect', () => {
    rl.question(`What is your name?\n\n `, (answer) => {
      socket.emit("message", `${chalk.green(answer)} has joined the chat`);
      id = answer;
      chat(socket);
    });
  });

  socket.on('msg', function(data){
    if(buffer!=data){
      console.log("\n" + data);
      chat(socket);
    }
  });
});

/* you can use socket in a function defined at the top level
 * if you pass it to that function as a parameter
 */
function chat(socket) {
  rl.question(chalk.magenta("» "), (answer) => {
      buffer = `${chalk.cyan(id)} : ${chalk.blue(answer)}`;
      socket.emit("message", buffer);
      chat(socket);
    });
}

Learning a lot about callbacks, promises, and Javascript's async / await is in your future.

Ad
source: stackoverflow.com
Ad