nodejs 边学边做之telnet 聊天工具
利用Net module 做的简单聊天工具,可以使用telnet 连接这个程序var net = require('net');
var config = {
separate : '\r\n'
};
var connections = new Object();
var server = net.createServer(function (c) {
var ip = c.remoteAddress;
var port = c.remotePort;
connections = c;
c.write('Welcome to chat room! your ip is ' + ip+port);
c.write(config.separate + 'I say:');
var buffers = [];
c.setEncoding('utf-8');
c.on('data', function (data) {
var index = data.indexOf(config.separate);
if (index < 0) {
buffers.push(data);
} else {
var contents = data.split(config.separate);
// contents + buffers will send
var buffer = '';
for (var i = 0, l = buffers.length; i < l; i++) {
buffer += buffers;
}
var message = contents + buffer;
buffers = [];
sendAll(c, message);
// contents will send
if (contents.length > 2) {
for (var i = 1, l = contents.length; i < l - 1; i++) {
sendAll(c, contents);
}
}
// contents will be push into buffers
buffers.push(new Buffer(contents));
}
});
c.on('close',function(){
delete connections;
});
});
function sendAll(conn, message) {
for (var address in connections) {
if(connections.hasOwnProperty(address)){
console.log(address);
if (conn != connections) {
console.log('other');
var what2say = config.separate + conn.remoteAddress + ':' + conn.remotePort +
'@[' + now() + '] said:' + message +
config.separate + 'I say: ';
connections.write(what2say);
} else {
console.log('self');
connections.write(config.separate + 'I say: ');
}
}
}
}
function now() {
var date = new Date();
hour = date.getHours();
min = date.getMinutes();
sec = date.getSeconds();
return hour + ':' + min + ':' + sec;
}
server.listen(8888, function () {
console.log('listen to 8888....');
});
上周末又做了一个网页版的, 一会上传。
页:
[1]