AChannel.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. namespace KYFramework.Network
  5. {
  6. public enum ChannelType
  7. {
  8. Connect,
  9. Accept,
  10. }
  11. public abstract class AChannel : ComponentWithId
  12. {
  13. public ChannelType ChannelType { get; }
  14. public AService Service { get; }
  15. public abstract MemoryStream Stream { get; }
  16. public int Error { get; set; }
  17. public IPEndPoint RemoteAddress { get; protected set; }
  18. private Action<AChannel, int> errorCallback;
  19. private Action<MemoryStream> readCallback;
  20. public event Action<AChannel, int> ErrorCallback
  21. {
  22. add
  23. {
  24. this.errorCallback += value;
  25. }
  26. remove
  27. {
  28. this.errorCallback -= value;
  29. }
  30. }
  31. public event Action<MemoryStream> ReadCallback
  32. {
  33. add
  34. {
  35. this.readCallback += value;
  36. }
  37. remove
  38. {
  39. this.readCallback -= value;
  40. }
  41. }
  42. protected void OnRead(MemoryStream memoryStream)
  43. {
  44. this.readCallback.Invoke(memoryStream);
  45. }
  46. protected void OnError(int e)
  47. {
  48. this.Error = e;
  49. this.errorCallback?.Invoke(this, e);
  50. }
  51. protected AChannel(AService service, ChannelType channelType)
  52. {
  53. this.Id = IdGenerater.GenerateId();
  54. this.ChannelType = channelType;
  55. this.Service = service;
  56. Log.Info("AChannel init...");
  57. }
  58. public abstract void Start();
  59. public abstract void Send(MemoryStream stream);
  60. public override void Dispose()
  61. {
  62. if (this.IsDisposed)
  63. {
  64. return;
  65. }
  66. base.Dispose();
  67. this.Service.Remove(this.Id);
  68. }
  69. }
  70. }