我是node.js的菜鸟,按照" Node.js in action"中的示例进行操作。 我有一个关于一个例子的问题: 以下代码通过telnet实现一个简单的聊天服务器。当我写一条消息时,脚本应该向所有连接的客户端发送消息。
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join',function(id,client){
this.clients[id] = client;
this.subscriptions[id] = function(senderId,message){
if(id != senderId){
this.clients[id].write(message);
}
};
this.on('broadcast',this.subscriptions);
});
var server = net.createServer(function(client){
var id = client.remoteAddress+':'+client.remotePort;
client.on('connect',function(){
channel.emit('join',id,client);
});
client.on('data',function(data){
data = data.toString();
channel.emit('broadcast',id,data);
});
});
server.listen(8888);
但是当我尝试通过telnet连接并发送消息时,它无法正常工作。 谢谢
答案 0 :(得分:0)
我注意到了几个问题。请参阅代码中的注释。
var events = require('events');
var net = require('net');
var channel = new events.EventEmitter();
channel.clients = {};
channel.subscriptions = {};
channel.on('join',function(id, client) {
this.clients[id] = client;
this.subscriptions[id] = function(senderId,message) {
if(id != senderId)
this.clients[id].write(message);
};
//added [id] to "this.subscriptions"
//Before you were passing in the object this.subscriptions
//which is not a function. So that would have actually thrown an exception.
this.on('broadcast',this.subscriptions[id]);
});
var server = net.createServer(function(client) {
//This function is called whenever a client connects.
//So there is no "connect" event on the client object.
var id = client.remoteAddress+':'+client.remotePort;
channel.emit('join', id, client);
client.on('data',function(data) {
data = data.toString();
channel.emit('broadcast',id,data);
});
});
server.listen(8888);
另请注意:如果客户端断开连接而另一个客户端发送消息,则this.clients[id].write(message);
将引发异常。这是因为,截至目前,您还没有收听断开连接事件并删除不再连接的客户端。因此,您将尝试写入不再连接的客户端,这将抛出异常。我假设你还没有到达那里,但我想提一下。