SendMessageAsync

Task SendMessageAsync(EndPoint endPoint, string message, 
    CancellationToken cancellationToken = default)
  • Description: This method is used to send a message asynchronously to a specified endpoint (IP address and port) using the selected socket protocol (TCP or UDP). The operation does not block the main thread, ensuring that the application can continue processing other tasks while the message is being sent.

  • Parameters:

    • EndPoint endPoint: The target endpoint (IP address and port) to which the message will be sent.

    • string message: The content of the message to be sent.

    • CancellationToken cancellationToken (optional): This token can be used to cancel the message sending operation before it completes, providing a way to stop the operation if needed.

  • Returns: The method returns a Task, representing the asynchronous operation. The Task completes when the message has been successfully sent.


The SendMessageAsync() method is designed to send messages to a specific endpoint using either TCP or UDP. It ensures that the sending process runs asynchronously, preventing the main thread from being blocked.

  • TCP: If the protocol is TCP, the method sends the message to the provided endpoint. TCP guarantees reliable, ordered delivery of the message, ensuring that it reaches the target in the correct sequence.

  • UDP: If the protocol is UDP, the method sends the message as a datagram. UDP does not guarantee message delivery or order, but it offers faster transmission compared to TCP.

Once the method is called, it initiates the message transmission process. The use of CancellationToken allows for the cancellation of the message sending operation if necessary.


Important Notes:

  • Asynchronous Operation: This method is designed to run asynchronously, allowing the application to continue processing other tasks while waiting for the message transmission to complete.

  • Message Delivery: For TCP, the method ensures the message is reliably delivered, while UDP does not guarantee delivery but provides faster transmission.

  • Cancellation Support: The operation can be cancelled using the provided CancellationToken parameter.


Usages:

EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 2626);

socketServer.SendMessageAsync(endPoint, "Hello, Client!");

Last updated