Fix to close a tcp socket properly in any cases