Session.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. private AChannel channel;
  25. private readonly Dictionary<uint, Action<PacketInfo>> requestCallback = new Dictionary<uint, Action<PacketInfo>>();
  26. private readonly byte[] flagBytes = new byte[1];
  27. private readonly List<byte[]> byteses = new List<byte[]>() {new byte[0], new byte[0], new byte[0]};
  28. private readonly List<byte[]> rpcByteses = new List<byte[]>() { new byte[0], new byte[0], new byte[0], new byte[0] };
  29. public NetworkComponent Network
  30. {
  31. get
  32. {
  33. return this.GetParent<NetworkComponent>();
  34. }
  35. }
  36. public void Awake(NetworkComponent net, AChannel c)
  37. {
  38. this.channel = c;
  39. this.requestCallback.Clear();
  40. }
  41. public void Start()
  42. {
  43. this.StartRecv();
  44. }
  45. public override void Dispose()
  46. {
  47. if (this.Id == 0)
  48. {
  49. return;
  50. }
  51. long id = this.Id;
  52. base.Dispose();
  53. foreach (Action<PacketInfo> action in this.requestCallback.Values.ToArray())
  54. {
  55. action.Invoke(new PacketInfo());
  56. }
  57. this.channel.Dispose();
  58. this.Network.Remove(id);
  59. this.requestCallback.Clear();
  60. }
  61. public IPEndPoint RemoteAddress
  62. {
  63. get
  64. {
  65. return this.channel.RemoteAddress;
  66. }
  67. }
  68. public ChannelType ChannelType
  69. {
  70. get
  71. {
  72. return this.channel.ChannelType;
  73. }
  74. }
  75. private async void StartRecv()
  76. {
  77. while (true)
  78. {
  79. if (this.Id == 0)
  80. {
  81. return;
  82. }
  83. Packet packet;
  84. try
  85. {
  86. packet = await this.channel.Recv();
  87. if (this.Id == 0)
  88. {
  89. return;
  90. }
  91. }
  92. catch (Exception e)
  93. {
  94. Log.Error(e.ToString());
  95. continue;
  96. }
  97. try
  98. {
  99. this.Run(packet);
  100. }
  101. catch (Exception e)
  102. {
  103. Log.Error(e.ToString());
  104. }
  105. }
  106. }
  107. private void Run(Packet packet)
  108. {
  109. if (packet.Length < Packet.MinSize)
  110. {
  111. Log.Error($"message error length < {Packet.MinSize}, ip: {this.RemoteAddress}");
  112. this.Network.Remove(this.Id);
  113. return;
  114. }
  115. byte flag = packet.Flag();
  116. ushort opcode = packet.Opcode();
  117. PacketInfo packetInfo = new PacketInfo
  118. {
  119. Opcode = opcode,
  120. Bytes = packet.Bytes
  121. };
  122. if ((flag & 0xC0) > 0)
  123. {
  124. uint rpcId = packet.RpcId();
  125. packetInfo.RpcId = rpcId;
  126. packetInfo.Index = Packet.RpcIdIndex + 4;
  127. packetInfo.Length = (ushort)(packet.Length - packetInfo.Index);
  128. // flag第2位表示这是rpc返回消息
  129. if ((flag & 0x40) > 0)
  130. {
  131. Action<PacketInfo> action;
  132. if (!this.requestCallback.TryGetValue(rpcId, out action))
  133. {
  134. return;
  135. }
  136. this.requestCallback.Remove(rpcId);
  137. action(packetInfo);
  138. return;
  139. }
  140. }
  141. else
  142. {
  143. packetInfo.RpcId = 0;
  144. packetInfo.Index = Packet.RpcIdIndex;
  145. packetInfo.Length = (ushort)(packet.Length - packetInfo.Index);
  146. }
  147. this.Network.MessageDispatcher.Dispatch(this, packetInfo);
  148. }
  149. public Task<PacketInfo> Call(ushort opcode, byte[] bytes)
  150. {
  151. uint rpcId = ++RpcId;
  152. var tcs = new TaskCompletionSource<PacketInfo>();
  153. this.requestCallback[rpcId] = (packetInfo) =>
  154. {
  155. try
  156. {
  157. tcs.SetResult(packetInfo);
  158. }
  159. catch (Exception e)
  160. {
  161. tcs.SetException(new Exception($"Rpc Error: {opcode}", e));
  162. }
  163. };
  164. const byte flag = 0x80;
  165. this.SendMessage(flag, opcode, rpcId, bytes);
  166. return tcs.Task;
  167. }
  168. public Task<PacketInfo> Call(ushort opcode, byte[] bytes, CancellationToken cancellationToken)
  169. {
  170. uint rpcId = ++RpcId;
  171. var tcs = new TaskCompletionSource<PacketInfo>();
  172. this.requestCallback[rpcId] = (packetInfo) =>
  173. {
  174. try
  175. {
  176. tcs.SetResult(packetInfo);
  177. }
  178. catch (Exception e)
  179. {
  180. tcs.SetException(new Exception($"Rpc Error: {opcode}", e));
  181. }
  182. };
  183. cancellationToken.Register(() => { this.requestCallback.Remove(rpcId); });
  184. const byte flag = 0x80;
  185. this.SendMessage(flag, opcode, rpcId, bytes);
  186. return tcs.Task;
  187. }
  188. public void Send(ushort opcode, byte[] bytes)
  189. {
  190. if (this.Id == 0)
  191. {
  192. throw new Exception("session已经被Dispose了");
  193. }
  194. const byte flag = 0x00;
  195. this.SendMessage(flag, opcode, 0, bytes);
  196. }
  197. public void Reply(ushort opcode, uint rpcId, byte[] bytes)
  198. {
  199. if (this.Id == 0)
  200. {
  201. throw new Exception("session已经被Dispose了");
  202. }
  203. const byte flag = 0x40;
  204. this.SendMessage(flag, opcode, rpcId, bytes);
  205. }
  206. private void SendMessage(byte flag, ushort opcode, uint rpcId, byte[] bytes)
  207. {
  208. this.flagBytes[0] = flag;
  209. List<byte[]> bb;
  210. if (rpcId == 0)
  211. {
  212. bb = this.byteses;
  213. bb[0] = flagBytes;
  214. bb[1] = BitConverter.GetBytes(opcode);
  215. bb[2] = bytes;
  216. }
  217. else
  218. {
  219. bb = this.rpcByteses;
  220. bb[0] = flagBytes;
  221. bb[1] = BitConverter.GetBytes(opcode);
  222. bb[2] = BitConverter.GetBytes(rpcId);
  223. bb[3] = bytes;
  224. }
  225. #if SERVER
  226. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  227. if (this.Network.AppType == AppType.AllServer)
  228. {
  229. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  230. this.pkt.Length = 0;
  231. ushort index = 0;
  232. foreach (var byts in bb)
  233. {
  234. Array.Copy(byts, 0, this.pkt.Bytes, index, byts.Length);
  235. index += (ushort)byts.Length;
  236. }
  237. this.pkt.Length = index;
  238. session.Run(this.pkt);
  239. return;
  240. }
  241. #endif
  242. channel.Send(bb);
  243. }
  244. #if SERVER
  245. private Packet pkt = new Packet(ushort.MaxValue);
  246. #endif
  247. }
  248. }