Added check to close socket.