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....');
});
 上周末又做了一个网页版的, 一会上传。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值