socat readbytes 达到限制后结束行

socat readbytes 达到限制后结束行

我们想利用索卡特使基于行的流程可用:

socat SYSTEM:"echo \$\$;sed -u /^%/s/foo/bar/" \
  TCP-L:1234,fork,reuseaddr,readbytes=21,bind=localhost

这有效,但只有在readbytes达到限制之前才有效,因为最后一行被缩短,左侧(“SYSTEM”)直到下一行才有换行符。例如:

$ echo %foo | socat - tcp:localhost:1234
13047
%bar
$ echo foo w/o ^% | socat - tcp:localhost:1234
foo w/o ^%
$ echo %foo, here is a too long line | socat - tcp:localhost:1234
$ echo %foo | socat - tcp:localhost:1234
%bar, here is a too l%foo

echo \$\$为了演示只socat启动左侧一次并使其为多个客户端运行。这就是我们所需要的。但是,当右侧由于 而缩短时,有没有办法将换行符传递给左侧readbytes

更新时间:2019-03-15 00:05 UTC:

人们可能想要添加,pty,rawer到左边,然而,这对于readbytes达到限制的情况没有帮助。

socat 是 1.7.3.1,运行在 Debian 9、Linux 4.9.144 上。

答案1

解决该问题的一种方法是计算字节数,如果达到限制,则添加最后一个换行符。在 Bash 中,例如可以使用以下方法完成此操作(此处包括SYSTEM:问题中的部分):

!/bin/bash
readbytes=21 # the number used in the question
echo $$
while :; do
   read -r -N 1 || break
   count=$((count+1))
   echo "byte $count is '$REPLY'" >&2
   printf '%s' "$REPLY"
   ((count<readbytes)) || { [[ $REPLY == $'\n' ]] || printf '\n'; count=0; }
   [[ $REPLY != $'\n' ]] || count=0
done \
|sed -u /^%/s/foo/bar/

现在,如果我们socat使用此脚本运行,如下所示

socat EXEC:./script  TCP-L:1234,fork,reuseaddr,readbytes=21,bind=localhost

太长的行将附加一个换行符,因此可以通过以下方式处理sed

$ echo %foo | socat - tcp:localhost:1234
3811702
%bar
$ echo foo w/o ^% | socat - tcp:localhost:1234
foo w/o ^%
$ echo %foo, here is a too long line | socat - tcp:localhost:1234
%bar, here is a too l
$ echo %foo | socat - tcp:localhost:1234
%bar

相关内容