2

我正在研究一种反向代理。我将避免在这里解释完整的体系结构,但它要求一侧需要发送它接收数据的套接字的 ID。

一个简化的例子:

// 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();
            }
        })
    }
);

但我只想读取前 4 个字节。但是如果我在data事件中只收到 2 个字节怎么办?或者如果我收到更多数据(例如,从其他客户端转发的数据)怎么办?

所以问题是:

如何从流中读取 N 个第一个字节,然后在没有读取字节但有任何剩余数据的情况下通过管道传输流的其余部分?

4

0 回答 0