第一个nodejs简易聊天室
var net = require('net');var clients = [];function Client(stream) { this.name = null; this.stream = stream;}var server = net.createServer(function (stream) { stream.setEncoding('utf-8'); var address = stream.remoteAddress; var client = new Client(stream); if (address === '127.0.0.1') { client.name = 'system'; clients.push(client); } else { stream.write('请在10s内输入您的昵称!\n'); } var timeout = setTimeout(function () { if (client.name === null) { stream.write('对不起,您已经超时!\n'); stream.end(); } }, 10000); stream.on('data', function(data) { if (client.name === null) { var name = data.match(/\S+/); name = name[0]; var flag = false; for (var key in clients) { if (clients[key].name === name) { flag = true; stream.write('对不起,该昵称已被使用,请换个试试!\n'); break; } } if (flag) { return; } client.name = name; console.log(client.name, '进入聊天室'); stream.write('欢迎您进入聊天室!\n'); clients.forEach(function(c) { c.stream.write(client.name+' 进入聊天室!\n'); }); clients.push(client); return; } clients.forEach(function(c) { if (c !== client) { c.stream.write(client.name+" : "+data); } }); }); stream.on('end', function() { var position = -1; clients.forEach(function(c, index) { if (c === client) { position = index; } if (c !== client && client.name !== null) { c.stream.write(client.name+' 离开了!\n'); } }); stream.end(); if (position >= 0) { clients.splice(position, 1); } }); stream.on('error', function(err) { var position = -1; clients.forEach(function(c, index) { if (c === client) { position = index; } if (c !== client && client.name !== null) { c.stream.write(client.name+' 异常退出!\n'); } }); stream.end(); if (position >= 0) { clients.splice(position, 1); } });});server.listen(8000);