Session.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 ETModel
  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<IResponse> Call(IRequest request)
  154. {
  155. uint rpcId = ++RpcId;
  156. var tcs = new TaskCompletionSource<IResponse>();
  157. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  158. ushort opcode = opcodeTypeComponent.GetOpcode(request.GetType());
  159. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(request);
  160. this.requestCallback[rpcId] = (packetInfo) =>
  161. {
  162. try
  163. {
  164. if (packetInfo.RpcId != rpcId)
  165. {
  166. return;
  167. }
  168. Type responseType = opcodeTypeComponent.GetType(packetInfo.Opcode);
  169. object message = this.Network.MessagePacker.DeserializeFrom(responseType, packetInfo.Bytes, packetInfo.Index, packetInfo.Length);
  170. IResponse response = (IResponse)message;
  171. if (response.Error > ErrorCode.ERR_Exception)
  172. {
  173. throw new RpcException(response.Error, response.Message);
  174. }
  175. tcs.SetResult(response);
  176. }
  177. catch (Exception e)
  178. {
  179. tcs.SetException(new Exception($"Rpc Error: {packetInfo.Opcode}", e));
  180. }
  181. };
  182. const byte flag = 0x80;
  183. this.SendMessage(flag, opcode, rpcId, bytes);
  184. return tcs.Task;
  185. }
  186. public Task<IResponse> Call(IRequest request, CancellationToken cancellationToken)
  187. {
  188. uint rpcId = ++RpcId;
  189. var tcs = new TaskCompletionSource<IResponse>();
  190. OpcodeTypeComponent opcodeTypeComponent = this.Network.Entity.GetComponent<OpcodeTypeComponent>();
  191. ushort opcode = opcodeTypeComponent.GetOpcode(request.GetType());
  192. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(request);
  193. this.requestCallback[rpcId] = (packetInfo) =>
  194. {
  195. try
  196. {
  197. if (packetInfo.RpcId != rpcId)
  198. {
  199. return;
  200. }
  201. Type responseType = opcodeTypeComponent.GetType(packetInfo.Opcode);
  202. object message = this.Network.MessagePacker.DeserializeFrom(responseType, packetInfo.Bytes, packetInfo.Index, packetInfo.Length);
  203. IResponse response = (IResponse)message;
  204. if (response.Error > ErrorCode.ERR_Exception)
  205. {
  206. throw new RpcException(response.Error, response.Message);
  207. }
  208. tcs.SetResult(response);
  209. }
  210. catch (Exception e)
  211. {
  212. tcs.SetException(new Exception($"Rpc Error: {packetInfo.Opcode}", e));
  213. }
  214. };
  215. cancellationToken.Register(()=>this.requestCallback.Remove(rpcId));
  216. const byte flag = 0x80;
  217. this.SendMessage(flag, opcode, rpcId, bytes);
  218. return tcs.Task;
  219. }
  220. public Task<PacketInfo> Call(ushort opcode, byte[] bytes)
  221. {
  222. uint rpcId = ++RpcId;
  223. var tcs = new TaskCompletionSource<PacketInfo>();
  224. this.requestCallback[rpcId] = (packetInfo) =>
  225. {
  226. try
  227. {
  228. if (packetInfo.RpcId != rpcId)
  229. {
  230. return;
  231. }
  232. // 抛到外层不能再使用之前的byte[],因为那是Packet所有的,为了减少gc一直传到这个位置
  233. byte[] newBytes = new byte[packetInfo.Length + packetInfo.Index];
  234. Array.Copy(packetInfo.Bytes, 0, newBytes, 0, newBytes.Length);
  235. packetInfo.Bytes = newBytes;
  236. tcs.SetResult(packetInfo);
  237. }
  238. catch (Exception e)
  239. {
  240. tcs.SetException(new Exception($"Rpc Error: {opcode}", e));
  241. }
  242. };
  243. const byte flag = 0x80;
  244. this.SendMessage(flag, opcode, rpcId, bytes);
  245. return tcs.Task;
  246. }
  247. public Task<PacketInfo> Call(ushort opcode, byte[] bytes, CancellationToken cancellationToken)
  248. {
  249. uint rpcId = ++RpcId;
  250. var tcs = new TaskCompletionSource<PacketInfo>();
  251. this.requestCallback[rpcId] = (packetInfo) =>
  252. {
  253. try
  254. {
  255. if (packetInfo.RpcId != rpcId)
  256. {
  257. return;
  258. }
  259. // 抛到外层不能再使用之前的byte[],因为那是Packet所有的,为了减少gc一直传到这个位置
  260. byte[] newBytes = new byte[packetInfo.Length + packetInfo.Index];
  261. Array.Copy(packetInfo.Bytes, 0, newBytes, 0, newBytes.Length);
  262. packetInfo.Bytes = newBytes;
  263. tcs.SetResult(packetInfo);
  264. }
  265. catch (Exception e)
  266. {
  267. tcs.SetException(new Exception($"Rpc Error: {opcode}", e));
  268. }
  269. };
  270. cancellationToken.Register(() => { this.requestCallback.Remove(rpcId); });
  271. const byte flag = 0x80;
  272. this.SendMessage(flag, opcode, rpcId, bytes);
  273. return tcs.Task;
  274. }
  275. public void Send(IMessage message)
  276. {
  277. OpcodeTypeComponent opcodeTypeComponent = Game.Scene.GetComponent<OpcodeTypeComponent>();
  278. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  279. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);
  280. this.Send(opcode, bytes);
  281. }
  282. public void Reply(uint rpcId, IResponse message)
  283. {
  284. if (this.IsDisposed)
  285. {
  286. throw new Exception("session已经被Dispose了");
  287. }
  288. OpcodeTypeComponent opcodeTypeComponent = Game.Scene.GetComponent<OpcodeTypeComponent>();
  289. ushort opcode = opcodeTypeComponent.GetOpcode(message.GetType());
  290. byte[] bytes = this.Network.MessagePacker.SerializeToByteArray(message);
  291. const byte flag = 0x40;
  292. this.SendMessage(flag, opcode, rpcId, bytes);
  293. }
  294. public void Send(ushort opcode, byte[] bytes)
  295. {
  296. if (this.IsDisposed)
  297. {
  298. throw new Exception("session已经被Dispose了");
  299. }
  300. const byte flag = 0x00;
  301. this.SendMessage(flag, opcode, 0, bytes);
  302. }
  303. private void SendMessage(byte flag, ushort opcode, uint rpcId, byte[] bytes)
  304. {
  305. this.flagBytes[0] = flag;
  306. List<byte[]> bb;
  307. if (rpcId == 0)
  308. {
  309. bb = this.byteses;
  310. bb[0] = flagBytes;
  311. bb[1] = BitConverter.GetBytes(opcode);
  312. bb[2] = bytes;
  313. }
  314. else
  315. {
  316. bb = this.rpcByteses;
  317. bb[0] = flagBytes;
  318. bb[1] = BitConverter.GetBytes(opcode);
  319. bb[2] = BitConverter.GetBytes(rpcId);
  320. bb[3] = bytes;
  321. }
  322. #if SERVER
  323. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  324. if (this.Network.AppType == AppType.AllServer)
  325. {
  326. Session session = this.Network.Entity.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  327. this.pkt.Length = 0;
  328. ushort index = 0;
  329. foreach (var byts in bb)
  330. {
  331. Array.Copy(byts, 0, this.pkt.Bytes, index, byts.Length);
  332. index += (ushort)byts.Length;
  333. }
  334. this.pkt.Length = index;
  335. session.Run(this.pkt);
  336. return;
  337. }
  338. #endif
  339. channel.Send(bb);
  340. }
  341. #if SERVER
  342. private Packet pkt = new Packet(ushort.MaxValue);
  343. #endif
  344. }
  345. }