看了TCP的有关知识,写了个基于NET的聊天室。
<div class="jb51code">
<pre class="brush:js;">
var net = require('net');
var count = 0,users = {};
var server = net.createServer(function (conn) {
console.log('连接到');
conn.write(
"\r\n > welcome to node-chat!"
- "\r\n > " + count + " other people are connected at this time."
- "\r\n > please write your name and press enter: "
);
count++;
// 代表当前连接的昵称
var nickname;
console.log(conn);
conn.on('data',function (data) {
// 删除\r\n
// data = data.replace('\r\n',' ');
// 当前<a href="/tag/zhuce/" target="_blank" class="keywords">注册</a>的昵称不存在
if (!nickname) {
// <a href="/tag/yonghuming/" target="_blank" class="keywords">用户名</a>存在
if(users[data]) {
conn.write('nickname in use');
return;
} else {
// <a href="/tag/yonghuming/" target="_blank" class="keywords">用户名</a>给nickname
nickname = data;
users[nickname] = conn;
for (var i in users) {
users[i].write('\r\n > ' + nickname + ' join our room \r\n > I: ');
}
}
} else {
// 开始聊天
for (var i in users) {
if (i != nickname) {
users[i].write('\r\n > ' + nickname + ': ' + data);
}
}
}
});
conn.on('close',function () {
count--;
});
conn.setEncoding('utf8');
});
server.listen(3000,function () {
console.log('服务器监听端口3000');
})