0

I'm following the tutorial on this tutorial. Here's the code:

var net = require('net')

var chatServer = net.createServer()

chatServer.on('connection', function(client) {
client.write('Hi!\n');
client.write('Bye!\n');
console.log("got msg from http");  //added
client.end()
})

chatServer.listen(9000)

I placed a console.log between the bye and the client.end()

When I run it and hit port 9000, the console.log is outputed twice instead of once.

got msg from http
got msg from http

anyone know why?

Thanks

Zuzlx
  • 1,246
  • 14
  • 33
  • Once for each request - note your browser may be requesting a favicon or similar. – Marty Jul 14 '14 at 23:09
  • possible duplicate of [nodejs - http.createServer seems to call twice](http://stackoverflow.com/questions/11961902/nodejs-http-createserver-seems-to-call-twice) – Marty Jul 14 '14 at 23:10
  • Thanks everyone. I'm coming from the world of sugary asp.net to sugar-free zone. – Zuzlx Jul 15 '14 at 17:26

1 Answers1

1

I'm guessing you're using a browser to test your server. What you're seeing is two different incoming HTTP requests. Try the following code and you will likely see that there are two incoming HTTP requests:

var net = require('net')

var chatServer = net.createServer()

chatServer.on('connection', function(client) {
    client.write('Hi!\n');
    client.write('Bye!\n');

    console.log("got msg from http");  //added

    client.on('data', function (data) {
        console.log('data: \n%s', data)
    });

    client.end()
})

chatServer.listen(9000)

The two requests should be GET / and GET /favicon.ico, favicon.ico is the icon which is displayed on the browser tab and bookmarks etc.

Patrik Oldsberg
  • 1,540
  • 12
  • 14