KcpSocket.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. namespace IFramework.Net.KCP
  5. {
  6. public class KcpSocket : IKcpSocket
  7. {
  8. public event Action<byte[], int, int> onMessage;
  9. public IPEndPoint remotePoint;
  10. public IPEndPoint localPoint;
  11. private UdpClient _udp;
  12. public Socket socket { get { return _udp.Client; } }
  13. public void Close()
  14. {
  15. if (_udp != null)
  16. {
  17. _udp.Close();
  18. _udp = null;
  19. }
  20. }
  21. public void Connect(string host, int port)
  22. {
  23. IPHostEntry hostEntry = Dns.GetHostEntry(host);
  24. if (hostEntry.AddressList.Length == 0)
  25. {
  26. Log.E("Unable to resolve host: " + host);
  27. return;
  28. }
  29. var endpoint = hostEntry.AddressList[0];
  30. _udp = new UdpClient(endpoint.AddressFamily);
  31. _udp.Connect(host, port);
  32. remotePoint = (IPEndPoint)_udp.Client.RemoteEndPoint;
  33. localPoint = (IPEndPoint)_udp.Client.LocalEndPoint;
  34. Recv();
  35. }
  36. private void Recv()
  37. {
  38. if (_udp == null) return;
  39. _udp.BeginReceive(EndRecv, _udp);
  40. }
  41. private void EndRecv(IAsyncResult ar)
  42. {
  43. try
  44. {
  45. var bytes= _udp.EndReceive(ar, ref remotePoint);
  46. if (bytes.Length>0)
  47. {
  48. if (onMessage!=null)
  49. {
  50. onMessage(bytes, 0, bytes.Length);
  51. }
  52. }
  53. }
  54. catch (Exception ex)
  55. {
  56. Log.Exception(ex);
  57. }
  58. finally
  59. {
  60. Recv();
  61. }
  62. }
  63. public void Send(byte[] buffer, int length)
  64. {
  65. if (_udp != null)
  66. {
  67. try
  68. {
  69. _udp.Send(buffer, length);
  70. }
  71. catch (Exception ex)
  72. {
  73. Log.Exception(ex);
  74. }
  75. }
  76. }
  77. }
  78. }