AService.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. namespace ET
  5. {
  6. public abstract class AService: IDisposable
  7. {
  8. public ServiceType ServiceType { get; protected set; }
  9. public ThreadSynchronizationContext ThreadSynchronizationContext;
  10. // localConn放在低32bit
  11. private long connectIdGenerater = int.MaxValue;
  12. public long CreateConnectChannelId(uint localConn)
  13. {
  14. return (--this.connectIdGenerater << 32) | localConn;
  15. }
  16. public uint CreateRandomLocalConn()
  17. {
  18. return (1u << 30) | RandomHelper.RandUInt32();
  19. }
  20. // localConn放在低32bit
  21. private long acceptIdGenerater = 1;
  22. public long CreateAcceptChannelId(uint localConn)
  23. {
  24. return (++this.acceptIdGenerater << 32) | localConn;
  25. }
  26. public abstract void Update();
  27. public abstract void Remove(long id);
  28. public abstract bool IsDispose();
  29. protected abstract void Get(long id, IPEndPoint address);
  30. public abstract void Dispose();
  31. protected abstract void Send(long channelId, long actorId, MemoryStream stream);
  32. protected void OnAccept(long channelId, IPEndPoint ipEndPoint)
  33. {
  34. this.AcceptCallback.Invoke(channelId, ipEndPoint);
  35. }
  36. public void OnRead(long channelId, MemoryStream memoryStream)
  37. {
  38. this.ReadCallback.Invoke(channelId, memoryStream);
  39. }
  40. public void OnError(long channelId, int e)
  41. {
  42. this.Remove(channelId);
  43. this.ErrorCallback?.Invoke(channelId, e);
  44. }
  45. public Action<long, IPEndPoint> AcceptCallback;
  46. public Action<long, int> ErrorCallback;
  47. public Action<long, MemoryStream> ReadCallback;
  48. public void Destroy()
  49. {
  50. this.Dispose();
  51. }
  52. public void RemoveChannel(long channelId)
  53. {
  54. this.Remove(channelId);
  55. }
  56. public void SendStream(long channelId, long actorId, MemoryStream stream)
  57. {
  58. this.Send(channelId, actorId, stream);
  59. }
  60. public void GetOrCreate(long id, IPEndPoint address)
  61. {
  62. this.Get(id, address);
  63. }
  64. }
  65. }