See
Check if Socket is alive before send Between IO::Socket::INET's $sock->connected, or IO::Select's $sock->can_read and $sock->can_write, you ought to be able to put an "if (test){ } in your code. Which one is best depends on the exact structure of your code.