AChannel.cs 1.4 KB

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