server.js
var net = require('net'); var clientList = []; var HOST = '127.0.0.1'; var PORT = 6969; var server = net.createServer(); server.on('connection', function(client) { console.log('CONNECTED: ' + client.remoteAddress +':'+ client.remotePort); client.name = client.remoteAddress + ':' + client.remotePort; console.log(client); client.write('Hi ' + client.name + '! '); clientList.push(client); client.on('data', function(data) { broadcast(data, client); }); client.on('close', function() { clientList.splice(clientList.indexOf(client), 1); }); client.on('error', function(e) { console.log(e.errno); }); }); function broadcast(message, client) { var cleanup = []; for(var i=0;i<clientList.length;i+=1) { if(client !== clientList[i]) { if(clientList[i].writable){ clientList[i].write(client.name + " says " + message); }else{ cleanup.push(clientList[i]); clientList[i].destroy(); console.log(cleanup); } } } for(i=0;i<cleanup.length;i+=1) { clientList.splice(clientList.indexOf(cleanup[i]), 1) } } server.listen(PORT, HOST); console.log('Server listening on ' + HOST + ':' + PORT);
client.js
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 6969; var client = new net.Socket(); client.connect(PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT); // 建立连接后立即向服务器发送数据,服务器将收到这些数据 client.write('I am Chuck Norris!'); }); // 为客户端添加“data”事件处理函数 // data是服务器发回的数据 client.on('data', function(data) { console.log('DATA: ' + data); // 完全关闭连接 //client.destroy(); }); // 为客户端添加“close”事件处理函数 client.on('close', function() { console.log('Connection closed'); });