Created
July 30, 2016 06:54
-
-
Save limboinf/f7f3383087d98c27d540a295482d1a69 to your computer and use it in GitHub Desktop.
nodejs 简单的Chat demo.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by fangpeng on 16/7/30. | |
* node app.js | |
* Usage: telnet localhost 9000 | |
*/ | |
var net = require("net"); | |
//创建TCP服务器 | |
var chatServer = net.createServer(), | |
clientList = []; // 保存所有连接的客户端 | |
//调用on()方法来添加一个事件监听器 | |
//监听网络连接, 触发connection事件并callback 匿名函数 | |
chatServer.on("connection", function(client) { | |
/* | |
@client: 连接后新客户端所对应的TCP socket对象的引用 | |
*/ | |
client.write("欢迎进入聊天系统!\n"); | |
//新用户连接后广播欢迎信息 | |
client.name = "系统"; | |
broadcast("欢迎新用户登录!\n", client); | |
//为每个client对象添加name属性 | |
client.name = client.remoteAddress + ":" + client.remotePort; | |
//将新用户添加到clientList | |
clientList.push(client); | |
//在connection回调函数作用域中添加data事件监听器 | |
//每当client send data 给服务器时,这个事件将被触发 | |
client.on("data", function(data) { | |
broadcast(data, client) | |
}); | |
//client断开的处理 | |
client.on("end", function() { | |
clientList.splice(clientList.indexOf(client), 1) | |
}); | |
//异常处理 | |
client.on("error", function(e) { | |
console.log(e) | |
}) | |
}); | |
function broadcast(msg, client) { | |
var cleanup = []; | |
for(var i=0; i<clientList.length; i++) { | |
if(client != clientList[i]) { | |
//检查socket是否可写,以确保不会因为任何一个不可写的socket导致异常 | |
if(clientList[i].writeable) { | |
clientList[i].write(client.name + " : " + msg) | |
} else { | |
//如果发现socket不可写,加入待删除列表中 | |
//并通过destroy()方法将其关闭 | |
cleanup.push(clientList[i]); | |
clientList[i].destroy(); | |
} | |
} | |
} | |
// 在写入循环中删除死节点,清除垃圾索引 | |
for(i=0; i<cleanup.length; i++) { | |
clientList.splice(clientList.indexOf(cleanup[i]), 1) | |
} | |
} | |
chatServer.listen(9000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment