0

i try to learn node.js and try to create a new TCP Server connection. The code

var server = require('net').createServer(function(socket) {
  console.log('new connection');

  socket.setEncoding('utf8');

  socket.write("Hello! You can start typing. Type 'quit' to exit.\n");

  socket.on('data', function(data) {
    console.log('got:', data.toString());
    if (data.trim().toLowerCase() === 'quit') {
      socket.write('Bye bye!');
      return socket.end();
    }
    socket.write(data);
  });

  socket.on('end', function() {
    console.log('Client connection ended');
  });

}).listen(4001);  

look at the callback function, after then, they call listen method. What is this for kind of object.

1
  • 2
    Could you re-state your question? It's a bit difficult to understand in its current phrasing. Commented Apr 27, 2013 at 14:24

1 Answer 1

1

What it basically says is:

function myHandler(socket) {
   // everything up to socket.on('end')
}

var server = require('net').createServer(myHandler);
server.listen(4001);

So it's just creating a socket server with a handler function, and then make the server listen to port 4001.

Sign up to request clarification or add additional context in comments.

1 Comment

method listen() is a function from server object. I see. Thanks so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.