Jatin
Jatin

Reputation: 14269

when is the 'connect' event in nodejs net module emitted?

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?

Upvotes: 6

Views: 8133

Answers (2)

Fred
Fred

Reputation: 114

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.

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 181017

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.

Upvotes: 19

Related Questions