Javascript 简单Telnet聊天服务器nodejs

Javascript 简单Telnet聊天服务器nodejs,javascript,node.js,asynchronous,client-server,chat,Javascript,Node.js,Asynchronous,Client Server,Chat,我不熟悉node.js和异步编程,作为学习node.js和异步编程的第一个小项目,我编写了一个小型Telnet聊天服务器。程序运行正常,但我想知道这是否是在node.js(异步编程模型)中编写程序的正确方法 我认为这更适合我的工作 var tcp = require('net'); var Server = tcp.createServer(); var pwd=[]; // keep tracks of connected clients var ip=[];

我不熟悉node.js和异步编程,作为学习node.js和异步编程的第一个小项目,我编写了一个小型Telnet聊天服务器。程序运行正常,但我想知道这是否是在node.js(异步编程模型)中编写程序的正确方法


我认为这更适合我的工作
  var tcp = require('net');

    var Server = tcp.createServer();
    var pwd=[]; // keep tracks of connected clients 
    var ip=[];  // keeps tracks of connected clients IP address
    var Cpwd = "Rushabh"; // password that you require to login

      Server.on('connection'  ,function(conn){
        conn.setEncoding('utf-8');
        conn.write("Password:");// ask user for password on their terminal
        console.log("[" + conn.remoteAddress + "] has joined the chat");


      conn.on('data' , function(data){
        if(pwd.indexOf(conn)>-1){//check if it is an old client or a new client
          console.log("[" + conn.remoteAddress + "]:"  + data); 
          if(pwd.length > 0){ // check if atleast one client is connected

            sendMessage(conn , data);// broadcast message to all client connected 

          }
        }
        else{//if it is a new client then server should first check for password 
          data= data.toString('utf-8').trim();
          var message = " has joined the chat";
          if(Cpwd == data){ // if it is a new client than check for password
            pwd.push(conn); 
            ip.push(conn.remoteAddress);
            sendMessage(conn , message);
          }

          else {conn.write("Password rejected:" + data);conn.end();}// disconnect client 
        }

      }); 

      conn.on('end' , function() { // remove the client from reference array

       var i , client;
         for(i in pwd){
           client = pwd[i];
           if(!client.writable){
             pwd.splice(i,1);
             console.log(ip[i]+ " has left the chat");
             ip.splice(i,1);
           }
         }

     });

}); 

    function sendMessage(conn , message){ //function to send message to all connected client

      var i , client;
      for(i in pwd){
        client = pwd[i];
        if(client.writable){     
          if(conn === client){       
            client.write("[me]:" + message);         
          }      
          else
            client.write("[" + conn.remoteAddress +"]:" + message);
        }
        else{
          pwd.splice(i , 1);
          console.log(ip[i]+ " has left the chat");
          ip.splice(i,1);
        }   
      }
    }
    Server.listen(8000);