Error when showing user name (NodeJS)

0

I'm starting now in the world of Javascript and NodeJS and in that, when I was doing a mini-chat I came across the following error: At the time of printing the user name, after he uses the '/ nickname' command he leaves the name as empty "", and only shows the message, and from time to time it shows a part of the name along with the message. Here is the code line for the server:

var net = require('net');

var connections = [];

var broadcast = function(message, origin){
connections.forEach(function (connection){
    if (connection === origin) return;
    connection.write(message);
    });
};

net.createServer(function(connection){
    connections.push(connection);
connection.write('Hello, I am the server!');
connection.on('data', function (message){
    var command = message.toString();
    if (command.indexOf('/nickname') === 0){
        var nickname = command.replace('/nickname ', '');
        broadcast(connection.nickname + ' is now ' + nickname);
        connection.nickname = nickname;
        return;

    }
    broadcast(connection.nickname + message, connection);
    });
}).listen(3000);

And here's the line of code for the client:

var net = require('net');

var client = net.connect(3000);
client.on('connect', function(){
     client.write('Hello, I am the client');
});
client.on('data', function(message){
    console.log(message.toString());
});
process.stdin.on('readable', function(){
    var message = process.stdin.read();
    if(!message) 
         return;
    message = message.toString().replace(/\n/, '');
    client.write(message);
});

It's all working correctly, just this / nickname that is not going! Anyone who can collaborate will be of great help!

    
asked by anonymous 26.03.2018 / 00:56

0 answers