Session.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace Model
  8. {
  9. [ObjectSystem]
  10. public class SessionSystem : ObjectSystem<Session>, IAwake<NetworkComponent, AChannel>, IStart
  11. {
  12. public void Awake(NetworkComponent network, AChannel channel)
  13. {
  14. this.Get().Awake(network, channel);
  15. }
  16. public void Start()
  17. {
  18. this.Get().Start();
  19. }
  20. }
  21. public sealed class Session : Entity
  22. {
  23. private static uint RpcId { get; set; }
  24. public NetworkComponent network;
  25. private AChannel channel;
  26. private readonly Dictionary<uint, Action<PacketInfo>> requestCallback = new Dictionary<uint, Action<PacketInfo>>();
  27. private readonly List<byte[]> byteses = new List<byte[]>() {new byte[0], new byte[0], new byte[0]};
  28. public void Awake(NetworkComponent net, AChannel c)
  29. {
  30. this.network = net;
  31. this.channel = c;
  32. this.requestCallback.Clear();
  33. }
  34. public void Start()
  35. {
  36. this.StartRecv();
  37. }
  38. public override void Dispose()
  39. {
  40. if (this.Id == 0)
  41. {
  42. return;
  43. }
  44. long id = this.Id;
  45. base.Dispose();
  46. foreach (Action<PacketInfo> action in this.requestCallback.Values.ToArray())
  47. {
  48. action.Invoke(new PacketInfo());
  49. }
  50. this.channel.Dispose();
  51. this.network.Remove(id);
  52. this.requestCallback.Clear();
  53. }
  54. public IPEndPoint RemoteAddress
  55. {
  56. get
  57. {
  58. return this.channel.RemoteAddress;
  59. }
  60. }
  61. public ChannelType ChannelType
  62. {
  63. get
  64. {
  65. return this.channel.ChannelType;
  66. }
  67. }
  68. private async void StartRecv()
  69. {
  70. while (true)
  71. {
  72. if (this.Id == 0)
  73. {
  74. return;
  75. }
  76. Packet packet;
  77. try
  78. {
  79. packet = await this.channel.Recv();
  80. if (this.Id == 0)
  81. {
  82. return;
  83. }
  84. }
  85. catch (Exception e)
  86. {
  87. Log.Error(e.ToString());
  88. continue;
  89. }
  90. try
  91. {
  92. this.Run(packet);
  93. }
  94. catch (Exception e)
  95. {
  96. Log.Error(e.ToString());
  97. }
  98. }
  99. }
  100. private void Run(Packet packet)
  101. {
  102. if (packet.Length < Packet.MinSize)
  103. {
  104. Log.Error($"message error length < {Packet.MinSize}, ip: {this.RemoteAddress}");
  105. this.network.Remove(this.Id);
  106. return;
  107. }
  108. ushort headerSize = BitConverter.ToUInt16(packet.Bytes, 0);
  109. Header header = this.network.MessagePacker.DeserializeFrom<Header>(packet.Bytes, 2, headerSize);
  110. byte flag = header.Flag;
  111. PacketInfo packetInfo = new PacketInfo
  112. {
  113. Header = header,
  114. Index = (ushort)(headerSize + 2),
  115. Bytes = packet.Bytes,
  116. Length = (ushort)(packet.Length - 2 - headerSize)
  117. };
  118. // flag第2位表示这是rpc返回消息
  119. if ((flag & 0x40) > 0)
  120. {
  121. uint rpcId = header.RpcId;
  122. Action<PacketInfo> action;
  123. if (!this.requestCallback.TryGetValue(rpcId, out action))
  124. {
  125. return;
  126. }
  127. this.requestCallback.Remove(rpcId);
  128. action(packetInfo);
  129. return;
  130. }
  131. this.network.MessageDispatcher.Dispatch(this, packetInfo);
  132. }
  133. public Task<PacketInfo> Call(ushort opcode, byte[] bytes)
  134. {
  135. uint rpcId = ++RpcId;
  136. var tcs = new TaskCompletionSource<PacketInfo>();
  137. this.requestCallback[rpcId] = (packetInfo) =>
  138. {
  139. try
  140. {
  141. tcs.SetResult(packetInfo);
  142. }
  143. catch (Exception e)
  144. {
  145. tcs.SetException(new Exception($"Rpc Error: {opcode}", e));
  146. }
  147. };
  148. const byte flag = 0x80;
  149. this.SendMessage(flag, opcode, rpcId, bytes);
  150. return tcs.Task;
  151. }
  152. public Task<PacketInfo> Call(ushort opcode, byte[] bytes, CancellationToken cancellationToken)
  153. {
  154. uint rpcId = ++RpcId;
  155. var tcs = new TaskCompletionSource<PacketInfo>();
  156. this.requestCallback[rpcId] = (packetInfo) =>
  157. {
  158. try
  159. {
  160. tcs.SetResult(packetInfo);
  161. }
  162. catch (Exception e)
  163. {
  164. tcs.SetException(new Exception($"Rpc Error: {opcode}", e));
  165. }
  166. };
  167. cancellationToken.Register(() => { this.requestCallback.Remove(rpcId); });
  168. const byte flag = 0x80;
  169. this.SendMessage(flag, opcode, rpcId, bytes);
  170. return tcs.Task;
  171. }
  172. public void Send(ushort opcode, byte[] bytes)
  173. {
  174. if (this.Id == 0)
  175. {
  176. throw new Exception("session已经被Dispose了");
  177. }
  178. const byte flag = 0x00;
  179. this.SendMessage(flag, opcode, 0, bytes);
  180. }
  181. public void Reply(ushort opcode, uint rpcId, byte[] bytes)
  182. {
  183. if (this.Id == 0)
  184. {
  185. throw new Exception("session已经被Dispose了");
  186. }
  187. const byte flag = 0x40;
  188. this.SendMessage(flag, opcode, rpcId, bytes);
  189. }
  190. private void SendMessage(byte flag, ushort opcode, uint rpcId, byte[] bytes)
  191. {
  192. Header header = new Header
  193. {
  194. Opcode = opcode,
  195. RpcId = rpcId,
  196. Flag = flag
  197. };
  198. byte[] headerBytes = this.network.MessagePacker.SerializeToByteArray(header);
  199. byte[] headerLength = BitConverter.GetBytes((ushort)headerBytes.Length);
  200. this.byteses[0] = headerLength;
  201. this.byteses[1] = headerBytes;
  202. this.byteses[2] = bytes;
  203. channel.Send(this.byteses);
  204. }
  205. }
  206. }