SimpleKcpClient.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Buffers;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. #if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER
  7. namespace System.Net.Sockets.Kcp.Simple
  8. {
  9. /// <summary>
  10. /// 简单例子
  11. /// </summary>
  12. public class SimpleKcpClient : IKcpCallback
  13. {
  14. UdpClient client;
  15. public SimpleKcpClient(int port)
  16. : this(port, null)
  17. {
  18. }
  19. public SimpleKcpClient(int port, IPEndPoint endPoint)
  20. {
  21. client = new UdpClient(port);
  22. kcp = new SimpleSegManager.Kcp(2001, this);
  23. this.EndPoint = endPoint;
  24. BeginRecv();
  25. }
  26. public SimpleSegManager.Kcp kcp { get; }
  27. public IPEndPoint EndPoint { get; set; }
  28. public void Output(IMemoryOwner<byte> buffer, int avalidLength)
  29. {
  30. var s = buffer.Memory.Span.Slice(0, avalidLength).ToArray();
  31. client.SendAsync(s, s.Length, EndPoint);
  32. buffer.Dispose();
  33. }
  34. public async void SendAsync(byte[] datagram, int bytes)
  35. {
  36. kcp.Send(datagram.AsSpan().Slice(0, bytes));
  37. }
  38. public async ValueTask<byte[]> ReceiveAsync()
  39. {
  40. var (buffer, avalidLength) = kcp.TryRecv();
  41. while (buffer == null)
  42. {
  43. await Task.Delay(10);
  44. (buffer, avalidLength) = kcp.TryRecv();
  45. }
  46. var s = buffer.Memory.Span.Slice(0, avalidLength).ToArray();
  47. return s;
  48. }
  49. private async void BeginRecv()
  50. {
  51. var res = await client.ReceiveAsync();
  52. EndPoint = res.RemoteEndPoint;
  53. kcp.Input(res.Buffer);
  54. BeginRecv();
  55. }
  56. }
  57. }
  58. #endif