in reply to Netcat
I have never used netcat but an obvious thing to try is to define a specific "I have finished" message. When you script gets that it can close down.