继续从tcp服务器读取,直到收到某个消息

时间:2018-04-20 23:19:40

标签: bash shell tcp netcat

我有以下代码:

 echo "about to echo stuff 1";

 echo -e "foo\n" | nc localhost "${ql_server_port}" | while read response; do
         echo "response from server: $response";
         if [[ "$response" == "released" ]]; then
            echo "quicklock: Lock was released.";
            return 0;
         fi
   done;

 echo "about to echo stuff 2";

这是记录的内容:

about to echo stuff 1
response from server: received_data
about to echo stuff 2

我无法弄清楚为什么它不继续从netcat连接读取,似乎在收到第一条消息后停止阅读。任何人都知道如何继续阅读连接?

我的猜测是管道关闭是因为echo语句退出了?如果是这样的话,如何让它保持打开状态?

2 个答案:

答案 0 :(得分:2)

文件描述符重定向到救援

# make a copy of stdout
exec  3<&1
echo "about to echo stuff 1";

# read from fd 3
{ nc localhost 1234 <3 | while read response; do
    echo "response from server: $response";
    if [[ "$response" == "released" ]]; then
        echo "quicklock: Lock was released."
        break
    fi
done } &

# echo to stdout but redirect to fd 3
echo -e "foo\n" >3
echo -e "bar\n" >3
# close descriptor when done
exec  3<&-
# wait for comm to finish
sleep 2
echo "about to echo stuff 2";

输出

about to echo stuff 1
response from server: bin
response from server: gar
response from server: released
quicklock: Lock was released.
about to echo stuff 2

答案 1 :(得分:0)

这样可行,但如果可能的话,我正在寻找一种更简单的方法:

     local named_pipe="$HOME/.quicklock/named_pipes/$$";
     mkfifo ${named_pipe};

      tail -f ${named_pipe} | nc localhost "${ql_server_port}" | while read response; do
         echo "response from server: $response";
         if [[ "$response" == "released" ]]; then
            echo "quicklock: Lock was released.";
            return 0;
         fi
      done &
   fi


     echo -e "{\"quicklock\":true}\n" > ${named_pipe}
     wait;

有没有办法回应一些事情,但没有关闭这个过程?