SendMessageAsync

Task SendMessageAsync(string message, CancellationToken cancellationToken = default)
  • Description: The SendMessageAsync method is used to send a message asynchronously to the server. This method starts a background task to send the message to the specified destination and ensures that the message is successfully delivered. If an error occurs during the sending process, the method may return error information.

  • Parameters:

    • message (string): The message to be sent. This is the text message that will be transmitted to the server.

    • cancellationToken (CancellationToken, optional): A token used to cancel the sending operation. This parameter is used when the message sending needs to be canceled during the process.

  • Returns: This method returns a Task. The Task object can be used to wait for the completion of the sending operation.


Functionality:

The SendMessageAsync method sends the specified message to the server asynchronously. If there is a network error or cancellation request, the operation may not complete successfully. Once the message is sent successfully, the task completes, confirming that the message has been delivered to the server. Additionally, the CancellationToken parameter allows the sending operation to be canceled if needed.

  • Successful Sending: If the message is successfully sent, the method completes without throwing any errors.

  • Cancellation: If a cancellation is requested, the method will cancel the operation during the sending process, and the Task will be marked as canceled.


Important Notes:

  • Since this method works asynchronously, it does not block the main thread of the application.

  • If an error occurs during the sending process, an appropriate error message may be thrown.

  • The CancellationToken is optional, but it is recommended to use it if cancellation is needed during the operation.


Usages:

try
{
    string message = "Hello, Server!";
    await socketClient.SendMessageAsync(message);
    Console.WriteLine("Message sent successfully.");
}
catch (Exception exception)
{
    Console.WriteLine($"Message sending error: {exception.Message}");
}

The SendMessageAsync method is used to send a message asynchronously to the server, returning a Task to indicate the completion of the operation. This method allows the sending process to be canceled and handles errors appropriately.

Last updated