源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Node.js实现简单聊天服务器

  • 时间:2022-01-28 17:14 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Node.js实现简单聊天服务器
使用Nodejs是如此简单的实现了一个简单的聊天服务器 实现代码如下:
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();
      }
    }
  }
}
使用过程就是: 启动js
node chat.js
连接方式:telnet
telnet 127.0.0.1 9000
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部