1

Writing an HTTP simple server on top of Net node.js module, not using HTTP module.

I have a server listening at localhost:port with a socket opened.

socket.on('data', function(data){
    clientMsg += data;
});

Once I type the address in the browser I can see the GET request is in clientMsg.

In order to return a response I use:

 socket.on('close', function(){ something response generating here});

But this is not working well as it sends the response only once I click ESC or STOP in the browser.

So the question is, how can I know the browser finished sending the message and waits for a response, without closing the connection?

1 Answer 1

2

You would use the event connection instead of close. Event: 'connection'

Also, this is the structure that is documented for such a server:

var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
    console.log('server connected');
    c.on('end', function() {
        console.log('server disconnected');
    });
    c.write('hello\r\n');
    c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
    console.log('server bound');
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply, I saw that as well and couldn't understand, the c.pipe part, does it sends the input after the other side finished to stream the data ? Moreover, when I connect to 127.0.0.1:8124 in Firefox, it does show the HTTP request, but it seems firefox still tries to retrieve data
c.write('hello\r\n'); Sends hello trough the socket. Pipe is a bit different nodejs.org/docs/v0.6.6/api/all.html#stream.pipe
Ok, I am testing the pipe method, I will accept once I fully understand that is the answer, thanks.

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.