【z13区】nodejs原生态模块,写个聊天室
2016-04-05 09:01
537 查看
目的:用控制台实现个聊天室
使用模块:net,process
开始前的废话:对于初学者来说,先理解官方文档很重要。
有很多写聊天室的,大多引用的第三方模块,难免会增加新手学习负担,这里我只使用官方中的net和process模块。
希望能给新手,更好的理解这两个模块(net模块为主,process模块为辅)
正文:
项目主要就两个文件
server.js:服务器
client.js:客户端(可以多开)
下面来看看效果图:
使用模块: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); } }); }
下面来看看效果图:
相关文章推荐
- 揭秘DOM中data和nodeValue属性同步改变那些事
- 24. Swap Nodes in Pairs
- Nodejs积累
- Nodejs超方便更新方式
- (四)Electron 把boostrap控件当做桌面控件用
- 使用nvm让不同版本的Node.js共存
- ECMAScript 2015 (ES6) in Node.js(译)
- nodejs群聊和私聊
- 24. Swap Nodes in Pairs
- Node.js其他模块
- 深入浅出NodeJS笔记(五)---- Promise的序列执行
- 基于NodeJS的秘室聊天室
- LeetCode-24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- nodejs的安装及从测试
- Sublime Es6教程2-基本语法
- Sublime Es6教程1-环境搭建
- Nodejs之request 和 response 对象的具体介绍
- LeetCode 222. Count Complete Tree Nodes(完全二叉树节点数统计)
- 理解inode