40줄 코드의 node 단체 채팅 시스템

1562 단어
var net = require('net');
var count = 0,users={};
var server = net.createServer(function(conn){
    conn.setEncoding('utf8');
    conn.write(
        '
> welcome to \033[92mnode-chat\033[39m!'+ '
> '+count+' other people are connected at this time.'+ '
> please write your name and press enter ' ); count++; var nickname; conn.on('data',function(data){ data = data.replace('\r
',''); if(!nickname){ if(users[data]){ conn.write('\033[93m> nickname already in use please try again:\033[39m '); return; }else{ nickname = data; users[nickname] = conn; broadcast('\033[90m> '+ nickname +' joined the room\033[39m
'); } }else{ broadcast('\033[96m > '+nickname+' : \033[39m'+data+'
'); } }); function broadcast(msg,exceptMyself){ for(var key in users){ if(!exceptMyself||key!= nickname){ users[key].write(msg); } } } conn.on('close',function(){ count--; delete users[nickname]; broadcast('\033[90m> '+nickname+' left the room\033[39m
'); }) }); server.listen(3000,function(){ console.log('\033[96m server listening on *:3000\033[39m'); })

좋은 웹페이지 즐겨찾기