Session.cs 5.5 KB

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