From db5721abc30d4c2d1359f2a152c0d099fff35f20 Mon Sep 17 00:00:00 2001 From: Rodrigo Branas Date: Sun, 28 Aug 2016 15:19:07 -0300 Subject: [PATCH] Node.js - #6 - Core Modules - Net --- NodeJS_6_Net/client.js | 18 ++++++++++++++++++ NodeJS_6_Net/server.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 NodeJS_6_Net/client.js create mode 100644 NodeJS_6_Net/server.js diff --git a/NodeJS_6_Net/client.js b/NodeJS_6_Net/client.js new file mode 100644 index 00000000..89120875 --- /dev/null +++ b/NodeJS_6_Net/client.js @@ -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); +}); \ No newline at end of file diff --git a/NodeJS_6_Net/server.js b/NodeJS_6_Net/server.js new file mode 100644 index 00000000..db5e70e5 --- /dev/null +++ b/NodeJS_6_Net/server.js @@ -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); \ No newline at end of file