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.
byte[]
int
IPEndPoint
IPEndPoint representing the remote host to which to send the data.
Task<int>
A Task object that references the asynchronous operation. The Result property of the task will contain the number of bytes sent.
ArgumentNullException:
datagram is null.
ArgumentOutOfRangeException:
bytes is less than zero or greater than the length of datagram.
ObjectDisposedException:
The UdpClient has been closed.
SocketException:
An error occurred while sending datagram data.
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.
SendAsync sends data but does not guarantee delivery or order. It also does not provide error checking for delivery.
Connect on the UdpClient first. This can improve performance by establishing a default remote endpoint for subsequent send operations.
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);
// }
}
The UdpClient.SendAsync method has several overloads to accommodate different sending scenarios:
Task<int> SendAsync(byte[] datagram, int bytes): Sends UDP datagram data to a remote host without specifying the endpoint. Requires the client to be connected.Task<int> SendAsync(byte[] datagram, int bytes, string hostname, int port): Sends UDP datagram data to a remote host specified by hostname and port.