启动脚本app.js如下:
#!/usr/bin/env node
var events = require('events');var net = require('net');var channel = new events.EventEmitter();channel.clients = {};channel.subscriptions = {};
/*添加join事件的监听器,保存用户的client对象,以便程序可以将数据发送给用户*/
channel.on('join',function(id,client){ this.clients[id] = client;this.subscriptions[id] = function(senderId,message){
/*忽略发出这一广播数据的用户*/
if(id != senderId){ this.clients[id].write(message); }}
/*添加一个专门针对当前用户的broadcast事件监听器*/
this.on('broadcast',this.subscriptions[id]);
/*client连接进来,显示欢迎字幕,并统计当前client数量*/
var welcome = "Welcome!/n"+'Guests online: '+this.listeners('broadcast').length;client.write(welcome+'/n');
/*通知其它client用户,当前client用户进入聊天室*/
channel.emit('broadcast',id,id+' come in the chat./n');});
/*添加client用户离开的leave事件的监听器,通知所有人client用户离开了*/
channel.on('leave',function(id){ channel.removeListener( 'broadcast',this.subscriptions[id]); channel.emit('broadcast',id,id+' has left the chat./n');});
/*关闭聊天室,移出所有监听*/
channel.on('shutdown',function(){channel.emit('broadcast','','chat has shut down./n'); channel.removeAllListeners( 'broadcast');});
/*设置最大监听的数量,默认超过10个监听会*/
channel.setMaxListeners(50);
var server = net.createServer(function(client){ var id = client.remoteAddress + ':' + client.remotePort;console.log('client id '+id);
/*当有client用户连接到服务器上来时发出一个join事件*/
channel.emit('join',id,client); client.on('data',function(data){data = data.toString();console.log(data);
/*收到s字符,关闭聊天室*/
if(data == "s"){console.log(data);channel.emit('shutdown');}else{
/*广播聊天信息*/
channel.emit('broadcast',id,data);
}
});
/*添加client用户断开连接的监听事件*/
client.on('close',function(){channel.emit('leave',id); });});server.listen(3000);console.log('started ... ');
启动node服务:node app.js
操作系统命令行,输入命令,进入聊天室:telent 127.0.0.1 3000
多开几个命令窗口,查看效果。
新闻热点
疑难解答