手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >Node.js实现简单聊天服务器
Node.js实现简单聊天服务器
摘要:使用Nodejs是如此简单的实现了一个简单的聊天服务器实现代码如下:varnet=require('net');varchatServer=...

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

【Node.js实现简单聊天服务器】相关文章:

javascript实现简单的进度条

利用js实现禁止复制文本信息

nodejs实现遍历文件夹并统计文件大小

Webpack 实现 AngularJS 的延迟加载

使用node+vue.js实现SPA应用

基于jQuery插件实现环形图标菜单旋转切换特效

jQuery实现的多屏图像图层切换效果实例

javascript实现可全选、反选及删除表格的方法

javascript实现动态改变层大小的方法

js实现字符串转日期格式的方法

精品推荐
分类导航