Wait for thread to end before closing the socket or an error is raised