Created
November 16, 2012 05:38
-
-
Save alejandro/4084473 to your computer and use it in GitHub Desktop.
ChatServer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var net = require('net'), sockets = {}, server | |
Object.defineProperty(global, 'socks', { | |
get: function () { | |
return Object.keys(sockets) | |
} | |
}) | |
server = net.createServer(function (sock){ | |
sock.id = +new Date, sockets[sock.id] = sock | |
sock.write('Bienvenido, actualmente conectados ' + socks.length + ' clientes') | |
sock.on('data', writeLn) | |
sock.on('close', close) | |
function writeLn(line) { | |
line = line.toString() | |
socks.forEach(function (sk){ | |
sk = sockets[sk] | |
if (sk.id !== sock.id) sk.write(sock.id + ': ' + line) | |
}) | |
} | |
function close() { | |
delete sockets[sock.id] | |
try { sock.destroy() } catch (ex){} | |
} | |
}) | |
server.listen(9001, function (){ | |
console.log('[*] Chat server en %d', this.address().port) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var net = require('net') | |
var socket = net.createConnection(9001) | |
socket.on('data', function (dat){ console.log(dat.toString())}) | |
var stdin = process.openStdin() | |
stdin.on('data', function (dat){ | |
socket.write(dat.toString()) | |
process.stdout.write('\n:>') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment