Continous Communication with netcat

Viewed 282

I have a bash script and i need to communicate with a server with netcat. I want to do

1.Connect with nc
2.Read Answer
3.Decide what to do with answer
4.Send a data to server
5.Go back to 2

Here is my code. But It does not advance after echo $JOB_STRING | netcat $BAGLANTI $PORT

$(echo $JOB_STRING | netcat $BAGLANTI $PORT)  
  read line    
  if [[ $line == "2.7" ]]; then
    echo Sunucu Verisyonu $line
---Send something to nc server
  else
    echo "İş geldi"
---Send something to nc server
  fi

I've also tried to store response in a variable but that didn't work too

    RESPONSE="$(echo $JOB_STRING | nc $BAGLANTI $PORT)"
  if [[ $RESPONSE "2.7" ]]; then
    echo Sunucu Verisyonu $line
  else
    echo "İş geldi"
  fi
2 Answers

Try with this:

while read line; do

  if [[ $line == "2.7" ]]; then
    echo Sunucu Verisyonu $line
  else
    echo "İş geldi"
  fi

done < $(echo $JOB_STRING | netcat $BAGLANTI $PORT) 

Edit:

echo $JOB_STRING | netcat $BAGLANTI $PORT | while read line; do

  if [[ $line == "2.7" ]]; then
    echo Sunucu Verisyonu $line
  else
    echo "İş geldi"
  fi

done

So run the command in the background and connect two fifos to it - one for reading, the other for writing - and use those two fifos to communicate with the background process. The background process is, of course, the netcat instance. With newer bash, coproc is a built-in command that does just that, and it's just trivial to use.

coproc netcat $BAGLANTI $PORT
echo JOB something >&"${COPROC[1]}"
IFS= read -r line  <&"${COPROC[0]}"
if something; then
    echo some response >&"${COPROC[1]}"
fi
exec {COPROC[0]}>&- {COPROC[1]>&-
kill $COPROC_PID
Related