您的位置:首页 > Web前端 > Node.js

【z13区】nodejs原生态模块,写个聊天室

2016-04-05 09:01 537 查看
目的:用控制台实现个聊天室

使用模块:net,process

开始前的废话:对于初学者来说,先理解官方文档很重要。

有很多写聊天室的,大多引用的第三方模块,难免会增加新手学习负担,这里我只使用官方中的net和process模块。

希望能给新手,更好的理解这两个模块(net模块为主,process模块为辅)

正文:

项目主要就两个文件

server.js:服务器

client.js:客户端(可以多开)

/*server.js*/
var net=require('net');
var server=net.createServer(),
clientList=[];
//clientList 保存连接的所有客户端
var options={"host":"127.0.0.1","port":"1117"};

/*给数组添加一个方法,判断obj是否存在此数组中*/
Array.prototype.contains=function (obj) {
for (var i = 0; i < this.length; i++) {
if(this[i]===obj){
return true;
}
}
return false;
}

server.on('connection',function (client) {
client.name=client.remoteAddress+':'+client.remotePort;
console.log(client.name+' 已经连接');
if(!clientList.contains(client)){
clientList.push(client);
}
client.on('data',function (data) {
console.log(client.name+' '+data);
//将此客户端的信息,发送给 除此客户端 的所有客户端
for (var i = 0; i < clientList.length; i++) {
if(client!==clientList[i]){
clientList[i].write(clientList[i].name+' '+data);
}
}
});

client.on('error',function () {
console.log(this.name+' 发生异常');
});
client.on('end',function(){
console.log(this.name+' 断开连接');
//这里需要将此 client 从lientList中移除
});

});


/*client.js*/
var net=require('net');
var options={"host":"127.0.0.1","port":1117};

var client=net.connect(options,function(){
console.log("客户端已连接");
consoleRead(client);
});

client.on('data',function (data) {
console.log(data.toString());
});

/*因为nodejs控制台运行后,默认是不支持输入的。
需要使用 process.stdin.resume().让其可以接收输入信息
process.stdin.on('data',Function)获取输入的内容
如果不需要再输入时,需要用process.stdin.pause()来停止接受输入信息。
参数 client:当前客户端
*/
function consoleRead(client){
process.stdin.resume();
console.log("输入聊天内容:");
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
//process.stdin.pause();
if(chunk.trim()==="end"){
console.log('已断开和服务器的连接');
client.end();
}else{
client.write(chunk);
}
});

}


下面来看看效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: