NoneUdpProxy.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using STUN.Interfaces;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace STUN.Proxy
  10. {
  11. public class NoneUdpProxy : IUdpProxy
  12. {
  13. public TimeSpan Timeout
  14. {
  15. get => TimeSpan.FromMilliseconds(UdpClient.Client.ReceiveTimeout);
  16. set => UdpClient.Client.ReceiveTimeout = Convert.ToInt32(value.TotalMilliseconds);
  17. }
  18. public IPEndPoint LocalEndPoint => (IPEndPoint)UdpClient.Client.LocalEndPoint;
  19. protected UdpClient UdpClient;
  20. public NoneUdpProxy(IPEndPoint local)
  21. {
  22. UdpClient = local == null ? new UdpClient() : new UdpClient(local);
  23. }
  24. public Task ConnectAsync(CancellationToken token = default)
  25. {
  26. return Task.CompletedTask;
  27. }
  28. public Task DisconnectAsync(CancellationToken token = default)
  29. {
  30. UdpClient.Close();
  31. return Task.CompletedTask;
  32. }
  33. public async Task<(byte[], IPEndPoint, IPAddress)> ReceiveAsync(byte[] bytes, IPEndPoint remote, EndPoint receive, CancellationToken token = default)
  34. {
  35. var localEndPoint = (IPEndPoint)UdpClient.Client.LocalEndPoint;
  36. Debug.WriteLine($@"{localEndPoint} => {remote} {bytes.Length} 字节");
  37. await UdpClient.SendAsync(bytes, bytes.Length, remote);
  38. var res = new byte[ushort.MaxValue];
  39. var flag = SocketFlags.None;
  40. var length = UdpClient.Client.ReceiveMessageFrom(res, 0, res.Length, ref flag, ref receive, out var ipPacketInformation);
  41. var local = ipPacketInformation.Address;
  42. Debug.WriteLine($@"{(IPEndPoint)receive} => {local} {length} 字节");
  43. return (res.Take(length).ToArray(),
  44. (IPEndPoint)receive
  45. , local);
  46. }
  47. public void Dispose()
  48. {
  49. UdpClient?.Dispose();
  50. }
  51. }
  52. }