DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Node.js實現簡單聊天服務器
Node.js實現簡單聊天服務器
編輯:關於JavaScript     

使用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

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved