Home > Web Front-end > JS Tutorial > Node.js implements a simple chat server_node.js

Node.js implements a simple chat server_node.js

WBOY
Release: 2016-05-16 16:43:53
Original
1365 people have browsed it

It’s so easy to implement a simple chat server using Nodejs

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){
    //数据发送给客户端
    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();
      }
    }
  }
}
Copy after login

The usage process is:

Start js

node chat.js
Copy after login

Connection method: telnet

telnet 127.0.0.1 9000
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template