主要代码是这样的: var net = require(“net”); var events = require(“events”); var channel = new events.EventEmitter(); channel.clients = {}; channel.subscriptions = [];
channel.on(‘join’,function(id,client){ console.log(‘has joined’); this.clients[id] = client; this.subscriptions[id] = function(senderid,message){ if (id != senderid) { this.clients[id].write(message); } } this.on(‘broadcast’,this.subscriptions[id]); });
var server = net.createServer(function(client){ var id = client.remoteAddress + “:” +client.remotePort; client.on(‘connect’,function(){ console.log(‘connect’); channel.emit(‘join’,id,client); });
client.on('data',function(data){
data = data.toString();
console.log('received data--->:'+data);
channel.emit('broadcast',id,data);
});
}); server.listen(3000); 测试的时候,发现加粗的代码没有执行,查了nodejs的api,net.socket是有connect事件的,不知道为啥没执行
亲,我觉得你理解错了吧.先看下官网对net.creatServer的说明 我写了一个小例子.说明 connect事件
你的意思我明白,一个服务端,一个客户端。net.socket的connect事件只能在客户端得到响应?
@zhang852774731 楼上已经说得很明白啦,net.createServer默认自动监听connect事件