It sounds to me like the real issue here is you aren't sure how to script it the proper way. Basically all you need to do is use a /sockmark instead of /sockclose after the final /sockwrite. This sockmark is the way you tell you are done writing to the socket and it can be closed when writing has finished. See the example that argv0 gave earlier because that's exactly what it does, and it doesn't add that many lines to your code.