UdpClient.SendAsync Method

public Task<int> SendAsync(byte[] datagram, int bytes, IPEndPoint remoteEP)

Sends datagram data to a remote host asynchronously using UDP.

This method sends UDP datagram data to a remote host specified by the IPEndPoint. The send operation is asynchronous and returns a Task that completes when the datagram has been sent.

Parameters

Return Value

Task<int>
A Task object that references the asynchronous operation. The Result property of the task will contain the number of bytes sent.

Exceptions

Remarks

The SendAsync method allows you to send UDP data without blocking the calling thread. This is crucial for applications that need to remain responsive, such as network servers or real-time communication tools.

When using SendAsync, you should typically wait for the returned Task to complete before proceeding, or use await to handle the asynchronous operation elegantly.

The underlying socket is bound to a local port. If the UdpClient is not bound, it will be bound to a default port automatically when you call SendAsync.

Note: UDP is a connectionless protocol. SendAsync sends data but does not guarantee delivery or order. It also does not provide error checking for delivery.
Tip: For scenarios where you are frequently sending to the same remote endpoint, consider calling Connect on the UdpClient first. This can improve performance by establishing a default remote endpoint for subsequent send operations.

Example

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class UdpSender
{
    public static async Task SendMessageAsync(string message, string ipAddress, int port)
    {
        using (UdpClient udpClient = new UdpClient())
        {
            try
            {
                byte[] messageBytes = Encoding.UTF8.GetBytes(message);
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);

                Console.WriteLine($"Sending message '{message}' to {remoteEndPoint}...");

                int bytesSent = await udpClient.SendAsync(messageBytes, messageBytes.Length, remoteEndPoint);

                Console.WriteLine($"Successfully sent {bytesSent} bytes.");
            }
            catch (SocketException e)
            {
                Console.WriteLine($"Socket exception: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"An error occurred: {e.Message}");
            }
        }
    }

    // Example usage:
    // public static async Task Main(string[] args)
    // {
    //     await SendMessageAsync("Hello, UDP!", "127.0.0.1", 11000);
    // }
}

Overloads

The UdpClient.SendAsync method has several overloads to accommodate different sending scenarios: