Skip to content

Commit

Permalink
Node.js - #6 - Core Modules - Net
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigobranas committed Aug 28, 2016
1 parent 996694f commit db5721a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
18 changes: 18 additions & 0 deletions NodeJS_6_Net/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
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());
});
client.on('end', function () {
process.exit();
});
process.stdin.on('readable', function () {
var message = process.stdin.read();
if (!message) return;
message = message.toString().replace(/\n/, '');
client.write(message);
});
29 changes: 29 additions & 0 deletions NodeJS_6_Net/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
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);
});
connection.on('end', function () {
broadcast(connection.nickname + ' has left!', connection);
connections.splice(connections.indexOf(connection), 1);
});
}).listen(3000);

1 comment on commit db5721a

@AlisonVilela
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tive problema ao executar no windows onde o nick não aparecia ao ser alterado, identifiquei que era devido a um \r que era inserido junto ao nick, então alterei a linha 18 do Server.JS para:
var nickname = command.replace('/nickname ', '').replace('\r', '');

Gostaria de saber se há uma solução melhor ou se é isso mesmo

Please sign in to comment.