Check that connection is still valid before sending/retrying
Since another thread might close the socket, make sure after the lock is acquired that the connection is still valid.
Add global declaration for completeness