AChannel.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Sockets;
  4. using System.Threading.Tasks;
  5. namespace Base
  6. {
  7. [Flags]
  8. public enum PacketFlags
  9. {
  10. None = 0,
  11. Reliable = 1 << 0,
  12. Unsequenced = 1 << 1,
  13. NoAllocate = 1 << 2
  14. }
  15. public abstract class AChannel: IDisposable
  16. {
  17. public long Id { get; private set; }
  18. protected AService service;
  19. public string RemoteAddress { get; protected set; }
  20. private event Action<AChannel, SocketError> errorCallback;
  21. public event Action<AChannel, SocketError> ErrorCallback
  22. {
  23. add
  24. {
  25. this.errorCallback += value;
  26. }
  27. remove
  28. {
  29. this.errorCallback -= value;
  30. }
  31. }
  32. protected void OnError(AChannel channel, SocketError e)
  33. {
  34. this.errorCallback(channel, e);
  35. }
  36. protected AChannel(AService service)
  37. {
  38. this.Id = IdGenerater.GenerateId();
  39. this.service = service;
  40. }
  41. /// <summary>
  42. /// 发送消息
  43. /// </summary>
  44. public abstract void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
  45. public abstract void Send(List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
  46. /// <summary>
  47. /// 接收消息
  48. /// </summary>
  49. public abstract Task<byte[]> Recv();
  50. public virtual void Dispose()
  51. {
  52. if (this.Id == 0)
  53. {
  54. return;
  55. }
  56. this.service.Remove(this.Id);
  57. this.Id = 0;
  58. }
  59. }
  60. }