Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 906
Jatin Avatar asked Oct 13 '13 07:10

Jatin


1 Answers

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.

like image 98
Joachim Isaksson Avatar answered Oct 21 '22 13:10

Joachim Isaksson