Node.js implements a simple chat server

  • 2020-03-30 03:24:24
  • OfStack

Using Nodejs is so simple to implement a simple chat server

The implementation code is as follows:


var net = require('net');
 
var chatServer = net.createServer(),clientList = [];
 
chatServer.on("connection",function(client){
  client.name = client.remoteAddress + ":" + client.remotePort;
  client.write("Hi! "+client.name+" n");
  clientList.push(client);
 
  client.on("data",function(data){
    //Data is sent to the client
    broadcast(data,client);
    // clientList[i].write(data);
  });
 
  client.on("end",function(){
    clientList.splice(clientList.indexOf(client),1);
  });
 
  client.on("error",function(e){
    console.log(e)
  });
});
chatServer.listen(9000)
 
function broadcast(message,client){
  var cleanup = [];
  for(var i=0;i<clientList.length;i++){
    if(client != clientList[i]){
      if(clientList[i].writable){
        clientList[i].write(client.name = "says:"+message);
      }else{
        cleanup.push[clientList[i]];
        clientList[i].destory();
      }
    }
  }
}

The use process is:

Start the js


node chat.js

Connection: Telnet


telnet 127.0.0.1 9000


Related articles: