connect method

Future<DtlsConnection> connect(
  1. InternetAddress address,
  2. int port, {
  3. PskCallback? pskCallback,
  4. EcdsaKeys? ecdsaKeys,
  5. void eventListener(
    1. DtlsEvent event
    )?,
})

Establishes a DtlsClientConnection with a peer using the given address and port.

Either a pskCallback or ecdsaKeys, or both can be provided (in this case the peer will be offered both a PSK and an ECC cipher during the DTLS Handshake). If neither a pskCallback nor ecdsaKeys are given, an ArgumentError is thrown.

If a DtlsConnection to a peer with the given address and port already exists, that connection will be reused instead of opening a new one. If you want to establish a connection using different credentials, then you need to close the old connection first.

Implementation

Future<DtlsConnection> connect(InternetAddress address, int port,
    {PskCallback? pskCallback,
    EcdsaKeys? ecdsaKeys,
    void Function(DtlsEvent event)? eventListener}) async {
  if (pskCallback == null && ecdsaKeys == null) {
    throw ArgumentError("No DTLS client credentials have been provided.");
  }

  final key = getConnectionKey(address, port);
  final existingConnection = _connections[key];
  if (existingConnection != null && !existingConnection._closed) {
    return existingConnection;
  }

  final context = _createContext(
      hasPsk: pskCallback != null, hasEcdsaKey: ecdsaKeys != null);
  final session = createSession(_tinyDtls, address, port);

  final connection = DtlsClientConnection(this, session, context,
      pskCallback: pskCallback,
      ecdsaKeys: ecdsaKeys,
      eventListener: eventListener);
  _connections[key] = connection;
  _createTimeout(connection, context);

  final result = _tinyDtls.dtls_connect(context, session);

  if (result < 0) {
    throw DtlsException("An error occurred while trying to connect");
  }

  return connection._connectCompleter.future;
}