How to write to socket after end of input stream?

by Matt Tingen   Last Updated July 12, 2019 14:26 PM - source

I'm trying to write a very simple node TCP server which reads in the full input stream and writes out some function of the input. The output cannot be generated without the full input so the writes cannot be streamed as the input comes in. For simplicity sake in this post, I have omitted the actual transformation of the input and am just writing back the input.

My initial attempt was to write within the end event handler:

const net = require('net');

const server = net.createServer(async client => {
  let data = '';

  client.on('end', () => {
    client.write(data);
  });

  client.on('data', part => {
    data += part.toString();
  });

  client.pipe(client);
});

server.listen(8124);

But this results in a Socket.writeAfterFIN error "This socket has been ended by the other party" which led me to enabling allowHalfOpen because the docs seem to indicate that it separates the incoming and outgoing FIN packets.

const net = require('net');

const drain = client =>
  new Promise(resolve => {
    let data = '';

    client.on('end', () => {
      console.log('end');
      resolve(data);
    });

    client.on('data', part => {
      console.log('data');
      data += part.toString();
    });
  });

const server = net.createServer({ allowHalfOpen: true }, async client => {
  const req = await drain(client);
  client.end(req);
});

server.listen(8124);

This works when I use e.g. echo 'abc' | nc localhost 8124, but I'm not sure whether allowHalfOpen should be necessary here. Is there another way to write shortly after the end of the input stream?

Tags : node.js sockets


Answers 1


Using netcat instead of curl resolves the issue. e.g. echo 'abc' | nc localhost 8124. This is also more in line with what I need to do anyway since I don't need HTTP for this server.

Matt Tingen
Matt Tingen
July 12, 2019 05:36 AM

Related Questions


Nodejs websocket

Updated July 26, 2017 00:26 AM

How do I intercept outgoing tcp messages in node?

Updated April 28, 2017 00:26 AM



Pass nodejs post parameter to socket connection

Updated May 13, 2017 10:26 AM