Last active
June 14, 2018 13:56
-
-
Save MrFant/1d7042eef089b1944c8c00a7ba575997 to your computer and use it in GitHub Desktop.
a tcp server base on nodejs
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
/** | |
* a tcp server base on nodejs | |
* come from <<nodejs: javascript everywhere>> | |
* | |
*/ | |
// "use strict"; | |
var net = require('net'), | |
count=0, | |
users={}; | |
let server=net.createServer(function (conn) { | |
console.log('\033[90m new connection! \033[39m' ); | |
let nickname; | |
conn.write( | |
'\n > Welcome to \033[92mnode-chat\033[39m!'+ | |
'\n > '+count+' other people are connected at this time.'+ | |
'\n > Please write your name and press enter : ' | |
); | |
count++; | |
conn.on('data',function (data) { | |
// console.log(data.toString().replace('\r\n','')); | |
data=data.toString().replace('\r\n',''); | |
// the un-login user | |
if (!nickname) { | |
if (users[data]){ | |
conn.write('\033[93m> nickname already in use. try again:\033[39m '); | |
} | |
else { | |
nickname=data; | |
users[nickname]=conn; | |
// announce someone joined to all | |
// for (let i in users){ | |
// users[i].write('\033[90m > '+nickname+' joined this room\033[39m\n'); | |
// } | |
broadcast('\033[90m > '+nickname+' joined this room\033[39m\n'); | |
} | |
} | |
else { | |
// take this as message | |
// for (let i in users){ | |
// if (i!==nickname){ | |
// users[i].write('\033[96m > '+nickname+':\033[39m '+data+'\n'); | |
// } | |
// } | |
broadcast('\033[96m > '+nickname+':\033[39m '+data+'\n',true); | |
} | |
}); | |
conn.on('close',function () { | |
count--; | |
delete users[nickname]; | |
broadcast('\033[90m > '+nickname+' left the room\033[39m\n'); | |
}); | |
function broadcast(msg,exceptMyself) { | |
for (let i in users){ | |
if (!exceptMyself || i!==nickname){ | |
users[i].write(msg); | |
} | |
} | |
} | |
}); | |
server.listen(3000,function () { | |
console.log('\033[96m server listening on *:3000 \033[39m'); | |
}); |
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
{ | |
"name": "TcpChat", | |
"version": "0.0.1", | |
"description": "A simple TCP-Chat server", | |
"dependencies": { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment