Created
February 10, 2014 08:12
-
-
Save chemzqm/8912139 to your computer and use it in GitHub Desktop.
TCP server & client
This file contains hidden or 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 fs = require ('fs'); | |
var client = net.connect(3000, '127.0.0.1'); | |
var log = fs.createWriteStream('out.log'); | |
log.on('error', function(err) { | |
console.log(err); | |
}) | |
client.setEncoding('utf8'); | |
process.stdin.resume(); | |
client.on('connect', function(conn) { | |
client.pipe(process.stdout); | |
process.stdin.pipe(client); | |
client.pipe(log); | |
process.stdin.pipe(log); | |
}) | |
client.on('close', function(data) { | |
console.log('connection lost'); | |
log.close(); | |
process.exit(); | |
}) | |
This file contains hidden or 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 count = 0; | |
var users = {}; | |
var server = net.createServer(function(conn) { | |
var nick; | |
function broadcast (msg, exceptMySelf) { | |
Object.keys(users).forEach(function(name) { | |
if (exceptMySelf && nick === name) return; | |
users[name].write(msg); | |
}) | |
} | |
conn.write( | |
'\n > Welcome to \033[92mnode-chat\033[39m!' + | |
'\n > ' + count + ' peole are connected currently' + | |
'\n > type your name and press enter :' | |
); | |
count++; | |
conn.setEncoding('utf8'); | |
conn.on('data', function(data) { | |
if (!nick) { | |
nick = data.replace('\n', ''); | |
if (users[nick]) { | |
conn.write('nickname \033[90m' + nick + '\033[39m have been used, type another one:'); | |
nick = ''; | |
} else { | |
users[nick] = conn; | |
broadcast('\033[95m > user ' + nick + ' have logged in\033[39m\r\n'); | |
} | |
} | |
else { | |
broadcast('\033[95m' + nick + '\033[39m: ' + data, true); | |
} | |
}) | |
conn.on('close', function() { | |
count--; | |
delete users[nick]; | |
broadcast('\033[95m > user ' + nick + ' have logged out\033[39m\r\n'); | |
}) | |
}) | |
server.listen(3000, function() { | |
console.log('\033[95m server started \033[39m'); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment