UdpTransport.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. namespace Microsoft.Xna.Framework.Net
  5. {
  6. /// <summary>
  7. /// Provides a UDP-based implementation of the <see cref="INetworkTransport"/> interface for sending and receiving network data.
  8. /// </summary>
  9. public class UdpTransport : INetworkTransport
  10. {
  11. private readonly UdpClient udpClient;
  12. /// <summary>
  13. /// Initializes a new instance of the <see cref="UdpTransport"/> class.
  14. /// </summary>
  15. public UdpTransport()
  16. {
  17. udpClient = new UdpClient();
  18. }
  19. /// <summary>
  20. /// Receives data from the network in a blocking manner.
  21. /// </summary>
  22. /// <returns>A tuple containing the received data and the sender's endpoint.</returns>
  23. public (byte[] data, IPEndPoint sender) Receive()
  24. {
  25. // Call the async version and block until it completes
  26. return ReceiveAsync().GetAwaiter().GetResult();
  27. }
  28. /// <summary>
  29. /// Receives data from the network asynchronously.
  30. /// </summary>
  31. /// <returns>A task that represents the asynchronous operation. The result contains the received data and the sender's endpoint.</returns>
  32. public async Task<(byte[] data, IPEndPoint sender)> ReceiveAsync()
  33. {
  34. var result = await udpClient.ReceiveAsync();
  35. return (result.Buffer, result.RemoteEndPoint);
  36. }
  37. /// <summary>
  38. /// Sends data to the specified endpoint in a blocking manner.
  39. /// </summary>
  40. /// <param name="data">The data to send.</param>
  41. /// <param name="endpoint">The endpoint to send the data to.</param>
  42. public void Send(byte[] data, IPEndPoint endpoint)
  43. {
  44. // Call the async version and block until it completes
  45. SendAsync(data, endpoint).GetAwaiter().GetResult();
  46. }
  47. /// <summary>
  48. /// Sends data to the specified endpoint asynchronously.
  49. /// </summary>
  50. /// <param name="data">The data to send.</param>
  51. /// <param name="endpoint">The endpoint to send the data to.</param>
  52. /// <returns>A task that represents the asynchronous operation.</returns>
  53. public async Task SendAsync(byte[] data, IPEndPoint endpoint)
  54. {
  55. await udpClient.SendAsync(data, data.Length, endpoint);
  56. }
  57. /// <summary>
  58. /// Releases all resources used by the <see cref="UdpTransport"/> class.
  59. /// </summary>
  60. public void Dispose()
  61. {
  62. udpClient?.Close();
  63. udpClient?.Dispose();
  64. }
  65. }
  66. }