`
cobrano1
  • 浏览: 27952 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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[ip+port] = 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[0] + buffers will send
				var buffer = '';
				for (var i = 0, l = buffers.length; i < l; i++) {
					buffer += buffers[i];
				}
				var message = contents[0] + buffer;
				buffers = [];
				sendAll(c, message);
				// contents[n] will send
				if (contents.length > 2) {
					for (var i = 1, l = contents.length; i < l - 1; i++) {
						sendAll(c, contents[i]);
					}
				}
				// contents[last] will be push into buffers
				buffers.push(new Buffer(contents[contents.length - 1]));
			}
		});
		c.on('close',function(){
			delete connections[ip+port];
		});
	});


function sendAll(conn, message) {
	for (var address in connections) {
		if(connections.hasOwnProperty(address)){
			console.log(address);
			if (conn != connections[address]) {
				console.log('other');
				var what2say = config.separate + conn.remoteAddress + ':' + conn.remotePort +
					'@[' + now() + '] said:' + message +
					config.separate + 'I say: ';
				connections[address].write(what2say);
			} else {
				console.log('self');
				connections[address].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....');
});
 上周末又做了一个网页版的, 一会上传。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics