Improve socket closing behaviour

Socket only closes when all pending queries have returned or timed out.