nodejs中基于TCP协议时下的类IRC程序(中继聊天程序)

参考书目:《了不起的nodejs》

服务器代码:

var net = require('net');

var count = 0;
var users = {};

var server = net.createServer(function(conn){
	console.log('\033[90m	new connection! \033[39m');
	
	conn.setEncoding('utf8');
	var nickname;
	conn.write(
		'\n>welcom to \033[92mnode-chat\033[39m!'
		+ '\n' + count + '	other people are connected at this time.'
		+ '\n > please write your name and press enter:' 
	);
	count++;
	conn.on('data',function(data){
		data = data.replace('\r\n','');
		if(!nickname){
			if(users[data]){
				conn.write('\033[93m> nickname already in use. try again:\033[39m ');
				return;
			}else{
				nickname = data;
				users[nickname] = conn;
				broadcast('\033[90m > '+ nickname + '  joined the room\033[39m\n' );
			}
		}else{
			broadcast('\033[96m > ' + nickname + ':\033[39m ' + data + '\n',true);
		}
	
		console.log(data);
	});
	conn.on('close',function(){
		console.log('coming in the close handle');
		count--;
		delete users[nickname];
		broadcast('\033[90m > ' + nickname + 'left the room\033[39m\n',true);
		console.log('users =');
		for(var i in users)
		{
			console.log(i);
		}
		console.log('count = '+ count);
		console.log('-------------');
	});
	
	conn.on('error',function(err){
		console.log('coming in the handle: ' + err);
	});
	
	function broadcast(msg,exceptMyself){
		for(var i in users){
			if(!exceptMyself || i != nickname){
				users[i].write(msg);
			}
		}
	}
});


server.listen(3000,function(){
	console.log('\033[96m	server listening on * : 3000\033[39m');	
});


listen的回调函数是服务器运行开始就调用,createServer的回调函数是客户端链接成功之后才会调用



客户端代码:

var net = require('net');
var stdin = process.stdin;

var nickname;
var client = net.connect(3000,'localhost');
client.setEncoding('utf-8');
client.on('connect',function(){
	console.log('connect successfully');
	stdin.resume();
	stdin.setEncoding('utf8');
	stdin.on('data',handleData);
});

function handleData(data){
	if(!nickname)
	{
		nickname = data;
		nickname = nickname.replace('\r\n','');
	}
	client.write(data);
}

client.on('data',function(data){
	console.log(data);
});


运行截图:




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值