Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 基于Bash的Netcat-TCP编程_Linux_Bash_Tcp_Netcat - Fatal编程技术网

Linux 基于Bash的Netcat-TCP编程

Linux 基于Bash的Netcat-TCP编程,linux,bash,tcp,netcat,Linux,Bash,Tcp,Netcat,我正试图通过严格使用bash脚本进行一些基本的TCP客户端通信。我有netcat供我使用,因此到目前为止我已经编写了这个循环: nc 10.0.0.104 4646 | while read line do if [ "$line" == '{"cmd": 1}' ] then # Send text back to the TCP server echo '{"error": 0}' fi done 脚本可以成功连接到我正在使用的服务器应用程序,但我

我正试图通过严格使用bash脚本进行一些基本的TCP客户端通信。我有netcat供我使用,因此到目前为止我已经编写了这个循环:

nc 10.0.0.104 4646 | while read line
do
   if [ "$line" == '{"cmd": 1}' ]
   then
      # Send text back to the TCP server
      echo '{"error": 0}'
   fi
done

脚本可以成功连接到我正在使用的服务器应用程序,但我很难确定如何将文本发送回netcat进程。

使用Bash≥4您可以使用
coproc

#!/bin/bash

coproc nc { nc 10.0.0.104 4646; }

while [[ $nc_PID ]] && IFS= read -r -u${nc[0]} line; do
    case $line in
        ('{"cmd": 1}')
            printf >&${nc[1]} '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done
这避免了使用临时FIFO。如果没有coproc,我想剩下的唯一选择就是显式使用FIFO。下面是一个例子:

#!/bin/bash

mkfifo fifo_in

while IFS= read -r line; do
    case $line in
        ('{"cmd": 1}')
            printf '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done < <(nc 10.0.0.104 4646 < fifo_in) > fifo_in

这很可能是最甜蜜的解决方案

好东西。如果O.P.不能使用Bash4,这些特性在ksh中已经存在好几年了。但这取决于ksh的可用版本,但值得测试。O.P.可以避免在生产环境中安装新设备。祝大家好运。
#!/bin/bash

# open TCP connection, available on file descriptor 3
exec 3<> /dev/tcp/10.0.0.104/4646 || exit

while IFS= read -r -u3 line; do
    case $line in
        ('{"cmd": 1}')
            printf >&3 '%s\n' '{"error": 0}'
            ;;
        (*)
            printf >&2 '%s\n' "Received line:" "$line"
            ;;
    esac
done