sendMessage method

Future<PacketHeader> sendMessage({
  1. required PeerId dstPeerId,
  2. bool isConfirmable = false,
  3. int? messageId,
  4. Uint8List? payload,
  5. Duration? ackTimeout,
  6. Iterable<FullAddress>? useAddresses,
})
inherited

Sends a message to the specified destination peer.

This method sends a message to the specified destination peer, optionally requesting confirmation of delivery. It resolves the peer's addresses, creates the message, encrypts it, and sends it using the configured transports.

dstPeerId The ID of the destination peer. isConfirmable Whether the message should be sent confirmably, requiring an acknowledgement from the receiver. Defaults to false. messageId An optional message ID to use. If not provided, a random ID is generated. payload The data to be sent with the message. ackTimeout The duration to wait for an acknowledgement before timing out. If not specified, the default message TTL is used. useAddresses An optional list of addresses to use for sending the message. If not provided, the addresses are resolved using the dstPeerId.

Returns the header of the sent message.

Throws an ExceptionIsNotRunning if the router is not running. Throws an ExceptionUnknownRoute if the destination peer is not known or no addresses could be resolved.

Implementation

Future<PacketHeader> sendMessage({
  required PeerId dstPeerId,
  bool isConfirmable = false,
  int? messageId,
  Uint8List? payload,
  Duration? ackTimeout,
  Iterable<FullAddress>? useAddresses,
}) async {
  // Check if the router is running.
  if (isNotRunning) {
    throw const ExceptionIsNotRunning();
  }

  // Resolve the addresses for the destination peer.
  final addresses = useAddresses ?? resolvePeerId(dstPeerId);

  // If no addresses are found, throw an exception.
  if (addresses.isEmpty) {
    throw ExceptionUnknownRoute(dstPeerId);
  }

  // Create the message.
  final message = Message(
    header: PacketHeader(
      // Set the message type based on whether it is confirmable.
      messageType: isConfirmable
          ? PacketType.confirmable
          : PacketType.regular,
      issuedAt: _now,
      // Generate a message ID if one is not provided.
      id: messageId ?? genRandomInt(),
    ),

    srcPeerId: selfId,
    dstPeerId: dstPeerId,
    payload: payload,
  );

  // Seal the message using the crypto provider.
  final datagram = await crypto.seal(message.toBytes());

  // Send the message.
  if (isConfirmable) {
    // If the message is confirmable, send it and wait for an
    // acknowledgement.
    await sendDatagramConfirmable(
      messageId: message.header.id,
      datagram: datagram,
      addresses: addresses,
      ackTimeout: ackTimeout,
    );
  } else {
    // If the message is not confirmable, send it without waiting for an
    // acknowledgement.
    sendDatagram(addresses: addresses, datagram: datagram);
    _log('sent ${datagram.length} bytes to $addresses');
  }

  return message.header;
}