NoneUdpProxy.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace STUN.Proxy
  10. {
  11. 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 { get => (IPEndPoint)UdpClient.Client.LocalEndPoint; }
  19. protected UdpClient UdpClient;
  20. public Task ConnectAsync(IPEndPoint local, IPEndPoint remote)
  21. {
  22. UdpClient = local == null ? new UdpClient() : new UdpClient(local);
  23. return Task.CompletedTask;
  24. }
  25. public Task DisconnectAsync()
  26. {
  27. UdpClient.Close();
  28. return Task.CompletedTask;
  29. }
  30. public async Task<(byte[], IPEndPoint, IPAddress)> RecieveAsync(byte[] bytes, IPEndPoint remote, EndPoint receive)
  31. {
  32. var localEndPoint = (IPEndPoint)UdpClient.Client.LocalEndPoint;
  33. Debug.WriteLine($@"{localEndPoint} => {remote} {bytes.Length} 字节");
  34. await UdpClient.SendAsync(bytes, bytes.Length, remote);
  35. var res = new byte[ushort.MaxValue];
  36. var flag = SocketFlags.None;
  37. var length = UdpClient.Client.ReceiveMessageFrom(res, 0, res.Length, ref flag, ref receive, out var ipPacketInformation);
  38. var local = ipPacketInformation.Address;
  39. Debug.WriteLine($@"{(IPEndPoint)receive} => {local} {length} 字节");
  40. return (res.Take(length).ToArray(),
  41. (IPEndPoint)receive
  42. , local);
  43. }
  44. }
  45. }