NoneUdpProxy.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using STUN.Utils;
  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. private readonly UdpClient _udpClient;
  20. public NoneUdpProxy(IPEndPoint? local)
  21. {
  22. _udpClient = local is null ? new UdpClient() : new UdpClient(local);
  23. }
  24. public Task ConnectAsync(CancellationToken token = default)
  25. {
  26. return Task.CompletedTask;
  27. }
  28. public Task DisconnectAsync()
  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 (local, length, rec) = await _udpClient.Client.ReceiveMessageFromAsync(receive, res, SocketFlags.None);
  40. return (res.Take(length).ToArray(), rec, local);
  41. }
  42. public void Dispose()
  43. {
  44. _udpClient.Dispose();
  45. }
  46. }
  47. }