when is the 'connect' event in nodejs net

2019-02-24 10:42发布

问题:

I have this simple TCP server:

var net = require('net');

var server = net.createServer(function (socket) {

    socket.on('connect', function() {
        console.log("New client!");
    });

});

server.listen(8000, function(){
    console.log("server running...")
});

and then I have another file as client.js:

var net = require('net');

var client = net.connect({port: 8000},
    function() { 
    console.log('client connected');
});

client.on('error', console.error);

I run server in one terminal window and then I run client in other window and expect to see server log "New Client". Although, that doesn't happen. So, when is the 'connect' event exactly emitted?

回答1:

net.createServer sets the given function as a listener to the connection event.

In other words, on the server side, the socket is already connected when you get the callback, and the event you're trying to listen to isn't emitted on an already connected socket.



回答2:

I made a different test. The server object has "timeout" property. When you call the follow code:

server.setTimeout(500); //Now after 0,5 second you can call "connection" event. The default value is 120000.

But, I still have no idea what this change will cause.