Session.cs 5.8 KB

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