使用socat复用传入的TCP连接

Roy*_*yHB 5 socat

外部数据提供商与我们的一台服务器建立了TCP连接。

我想使用socat来“复用”传入的数据,以便多个程序可以接收从外部数据提供程序发送的数据。

socat -u TCP4-LISTEN:42000,reuseaddr,fork OPEN:/home/me/my.log,creat,append
Run Code Online (Sandbox Code Playgroud)

愉快地接受传入的数据并将其放入文件中。

我想做的是允许本地程序连接到TCP端口并开始接收从连接到外部端口的数据的操作。我试过了

socat -u TCP4-LISTEN:42000,reuseaddr,fork TCP4-LISTEN:43000,reuseaddr 
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我还没有在socat doco中找到任何与背对背TCP服务器相关的示例。

有人可以指出我正确的方向吗?

Tho*_*hor 5

使用Bash流程替代

通常,可以使用coreutils teeBash进程替换来实现从Shell进行复。因此,例如,将socat流多路复用到多个管道可以执行以下操作:

socat -u tcp-l:42000,fork,reuseaddr system:'bash -c \"tee >(sed s/foo/bar/ > a) >(cat > b) > /dev/null\"'
Run Code Online (Sandbox Code Playgroud)

现在,如果您发送foobar到服务器:

socat - tcp:localhost:42000 <<<fobar
Run Code Online (Sandbox Code Playgroud)

文件ab将包含:

一种

巴巴

b

foob​​ar

带命名管道

如果管道很复杂和/或您想避免使用Bash,则可以使用命名管道来提高可读性和可移植性:

mkfifo x y
Run Code Online (Sandbox Code Playgroud)

创建阅读器进程:

sed s/foo/bar/ x > a &
cat y > b &
Run Code Online (Sandbox Code Playgroud)

启动服务器:

socat -u tcp-l:42000,fork,reuseaddr system:'tee x y > /dev/null'
Run Code Online (Sandbox Code Playgroud)

再次,发送foobar到服务器:

echo foobar |  socat - tcp:localhost:42000
Run Code Online (Sandbox Code Playgroud)

结果与上面相同。