Alexander Mills
Alexander Mills

Reputation: 100010

child process writing to socket - localhost sent an invalid response

I have this in a parent process:

import cp = require('child_process');
const k = cp.fork(file);

 app.use(function(req,res,next){       
      k.send('handle', req.socket);       
 };

and then I have this in the child process:

process.on('message', function (m, socket) {

  if (m === 'handle' && socket) {
    socket.end('foobar!!!');
  }
  else{
    console.log('nope');
  }

});

After doing some logging, I know that socket.end('foobar!!!'); is getting called. But I see this error in the browser:

enter image description here

Anyone know how I can send a valid response with just a plain socket at my disposal?

I guess I need to learn how to actually write a valid HTTP response, never tried that before.

Upvotes: 0

Views: 617

Answers (1)

jfriend00
jfriend00

Reputation: 707328

When you do this:

socket.end('foobar!!!');

Your are just sending foobar!!! and that is not a valid http response which is exactly what your client error message is telling you.

Because you've passed this socket to another process and express has not yet written anything to that socket in the original process, you need to send a whole valid http response here.

An http response looks like this:

enter image description here

Credit to this article for the image.

So, a very simple http response could look like this:

socket.end('HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nHello');

Upvotes: 1

Related Questions