2

I'm working on a sort of reverse proxy. I'll avoid explaining the full architecture here, but it requires that one side needs to send ID of the socket from which it receives data.

A simplified example:

// This is an array of sockets that are waiting for connection
// from the other side
// They are indexed by ID
const sendingSockets = {};

const handlerServer = net.createServer(
    (socket) => {
        socket.on("data", (data) => {
            const clientID = data.readInt32LE(0);
            if (sockets[clientID]) {
                // remaining data is the data from local client
                // Can I even pipe sockets to each other like this?
                socket.pipe(sockets[clientID]);
                sockets[clientID].pipe(socket);
                // How do I stop listenning on data?
            }
            else {
                // Client already disconnected
                socket.close();
            }
        })
    }
);

But I only want to read first 4 bytes. But what if I only receive 2 bytes in the data event? Or what if I receive more data (eg. the data forwarded from the other client)?

So the question is:

How to read N first bytes from a stream, then pipe rest of the stream without the bytes read but with any remaining data?

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

0 Answers0