NodeJS net.socket 管道 condition/filter

NodeJS net.socket Pipe by condition/filter

我是 NodeJS 新手。现有的 net.socket 管道需要按条件过滤才能不连接到“con2”,我现有的代码如下。

我找到了 Transform 和 PipeLine 方法,到目前为止我已经尝试过,示例代码还不适用于我的场景。

条件是在“con1”读取流数据有一些关键字。例如“输出” 然后,不要将数据连接或转换为空数据到“con2”。这样,“con2”就不会被处理。

Start.js

import Proxy from "./Proxy.js";

const proxy = Proxy();
  proxy.listen('4000');

Proxy.js

import net from "net";

export default () =>
    net.createServer((con1) => {
        const con2 = net.connect(
          '1234',
          '127.0.0.1'
        );
        
        con1.pipe(con2).pipe(con1);
    
        con2.on("data", async (data) => {
          try {
                console.log("sent from con2:", data);
               }
          }
        }
        con1.on("data", async (data) => {
          try {
                console.log("sent from con1:", data);
               }
          }
        }

请帮忙指教。提前致谢。

我整理了一些东西:

const net = require("net");

const { Transform, pipeline } = require("stream");


const spy = (client) => {
    return new Transform({
        transform(chunk, encoding, cb) {
            if (chunk.toString("utf-8").includes("output")) {

                cb(new Error("ABORTED!"));

            } else {

                cb(null, chunk);

            }
        }
    });
};


let server = net.createServer((socket) => {

    const client = net.connect('1234', '127.0.0.1');

    pipeline(socket, spy(client), client, (err) => {
        console.log("pipeline closed", err);
    });

});

server.listen(1235, "127.0.0.1", () => {
    console.log("Go and send something to the tcp socket, tcp://127.0.0.1:1235")
});

启动一个简单的 netcat 服务器以查看我们向其发送的内容:

while true; do nc -l -p 1234; done;

当我们现在连接到另一个 netcat 时,我们可以通过代理将内容发送到另一个 netcat 实例:

nc 127.0.0.1 1235

当我们现在发送“输出”关键字时,连接得到 aborted/terminated。

间谍函数简单地检查通过管道中的转换流的块并检查字符串“output”,如果找到,则关闭管道并终止两个客户端 sockets/connections。