AChannel.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 enum ChannelType
  16. {
  17. Connect,
  18. Accept,
  19. }
  20. public abstract class AChannel: IDisposable
  21. {
  22. public long Id { get; private set; }
  23. public ChannelType ChannelType { get; }
  24. protected AService service;
  25. public string RemoteAddress { get; protected set; }
  26. private event Action<AChannel, SocketError> errorCallback;
  27. public event Action<AChannel, SocketError> ErrorCallback
  28. {
  29. add
  30. {
  31. this.errorCallback += value;
  32. }
  33. remove
  34. {
  35. this.errorCallback -= value;
  36. }
  37. }
  38. protected void OnError(AChannel channel, SocketError e)
  39. {
  40. this.errorCallback(channel, e);
  41. }
  42. protected AChannel(AService service, ChannelType channelType)
  43. {
  44. this.Id = IdGenerater.GenerateId();
  45. this.ChannelType = channelType;
  46. this.service = service;
  47. }
  48. /// <summary>
  49. /// 发送消息
  50. /// </summary>
  51. public abstract void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
  52. public abstract void Send(List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
  53. /// <summary>
  54. /// 接收消息
  55. /// </summary>
  56. public abstract Task<byte[]> Recv();
  57. public virtual void Dispose()
  58. {
  59. if (this.Id == 0)
  60. {
  61. return;
  62. }
  63. this.service.Remove(this.Id);
  64. this.Id = 0;
  65. }
  66. }
  67. }