using System;
using System.Net;
using System.Net.Sockets;
namespace Microsoft.Xna.Framework.Net
{
///
/// Provides a UDP-based implementation of the interface for sending and receiving network data.
///
public class UdpTransport : INetworkTransport
{
private readonly UdpClient udpClient;
///
/// Initializes a new instance of the class.
///
public UdpTransport()
{
udpClient = new UdpClient();
}
///
/// Receives data from the network in a blocking manner.
///
/// A tuple containing the received data and the sender's endpoint.
public (byte[] data, IPEndPoint sender) Receive()
{
// Call the async version and block until it completes
return ReceiveAsync().GetAwaiter().GetResult();
}
///
/// Receives data from the network asynchronously.
///
/// A task that represents the asynchronous operation. The result contains the received data and the sender's endpoint.
public async Task<(byte[] data, IPEndPoint sender)> ReceiveAsync()
{
var result = await udpClient.ReceiveAsync();
return (result.Buffer, result.RemoteEndPoint);
}
///
/// Sends data to the specified endpoint in a blocking manner.
///
/// The data to send.
/// The endpoint to send the data to.
public void Send(byte[] data, IPEndPoint endpoint)
{
// Call the async version and block until it completes
SendAsync(data, endpoint).GetAwaiter().GetResult();
}
///
/// Sends data to the specified endpoint asynchronously.
///
/// The data to send.
/// The endpoint to send the data to.
/// A task that represents the asynchronous operation.
public async Task SendAsync(byte[] data, IPEndPoint endpoint)
{
await udpClient.SendAsync(data, data.Length, endpoint);
}
///
/// Releases all resources used by the class.
///
public void Dispose()
{
udpClient?.Close();
udpClient?.Dispose();
}
}
}