Session.cs 9.2 KB

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