disconnect method

Future<void> disconnect()

Disconnect from the peer

Implementation

Future<void> disconnect() async {
  if (_state == ConnectionState.disconnected) {
    return;
  }

  _setState(ConnectionState.disconnecting);
  logger.info('Disconnecting from $address:$port...');

  try {
    // Stop send loop
    _sendLoopRunning = false;

    // Close socket
    await _socketSubscription?.cancel();
    _socketSubscription = null;

    await _socket?.close();
    _socket = null;

    // Wait for send loop to finish
    if (!_sendLoopCompleter.isCompleted) {
      await _sendLoopCompleter.future.timeout(const Duration(seconds: 5));
    }

    _setState(ConnectionState.disconnected);
    logger.info('Disconnected from $address:$port');

  } catch (e) {
    logger.warning('Error during disconnect from $address:$port: $e');
    _setState(ConnectionState.error);
  }
}