Session.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 NetworkComponent network;
  25. private AChannel channel;
  26. private readonly Dictionary<uint, Action<object>> requestCallback = new Dictionary<uint, Action<object>>();
  27. private readonly List<byte[]> byteses = new List<byte[]>() {new byte[0], new byte[0]};
  28. public void Awake(NetworkComponent net, AChannel c)
  29. {
  30. this.network = net;
  31. this.channel = c;
  32. this.requestCallback.Clear();
  33. }
  34. public void Start()
  35. {
  36. this.StartRecv();
  37. }
  38. public override void Dispose()
  39. {
  40. if (this.Id == 0)
  41. {
  42. return;
  43. }
  44. long id = this.Id;
  45. base.Dispose();
  46. foreach (Action<object> action in this.requestCallback.Values.ToArray())
  47. {
  48. action.Invoke(new ErrorResponse() { Error = ErrorCode.ERR_SocketDisconnected });
  49. }
  50. this.channel.Dispose();
  51. this.network.Remove(id);
  52. this.requestCallback.Clear();
  53. }
  54. public IPEndPoint RemoteAddress
  55. {
  56. get
  57. {
  58. return this.channel.RemoteAddress;
  59. }
  60. }
  61. public ChannelType ChannelType
  62. {
  63. get
  64. {
  65. return this.channel.ChannelType;
  66. }
  67. }
  68. private async void StartRecv()
  69. {
  70. while (true)
  71. {
  72. if (this.Id == 0)
  73. {
  74. return;
  75. }
  76. Packet packet;
  77. try
  78. {
  79. packet = await this.channel.Recv();
  80. if (this.Id == 0)
  81. {
  82. return;
  83. }
  84. }
  85. catch (Exception e)
  86. {
  87. Log.Error(e.ToString());
  88. continue;
  89. }
  90. if (packet.Length < 2)
  91. {
  92. Log.Error($"message error length < 2, ip: {this.RemoteAddress}");
  93. this.network.Remove(this.Id);
  94. return;
  95. }
  96. ushort opcode = BitConverter.ToUInt16(packet.Bytes, 0);
  97. try
  98. {
  99. this.RunDecompressedBytes(opcode, packet.Bytes, 2, packet.Length);
  100. }
  101. catch (Exception e)
  102. {
  103. Log.Error(e.ToString());
  104. }
  105. }
  106. }
  107. private void RunDecompressedBytes(ushort opcode, byte[] messageBytes, int offset, int count)
  108. {
  109. object message;
  110. try
  111. {
  112. Type messageType = this.network.Parent.GetComponent<OpcodeTypeComponent>().GetType(opcode);
  113. message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, count - offset);
  114. }
  115. catch (Exception e)
  116. {
  117. Log.Error($"message deserialize error, ip: {this.RemoteAddress} {opcode} {e}");
  118. this.network.Remove(this.Id);
  119. return;
  120. }
  121. //Log.Debug($"recv: {MongoHelper.ToJson(message)}");
  122. AResponse response = message as AResponse;
  123. if (response != null)
  124. {
  125. // rpcFlag>0 表示这是一个rpc响应消息
  126. // Rpc回调有找不着的可能,因为client可能取消Rpc调用
  127. Action<object> action;
  128. if (!this.requestCallback.TryGetValue(response.RpcId, out action))
  129. {
  130. return;
  131. }
  132. this.requestCallback.Remove(response.RpcId);
  133. action(message);
  134. return;
  135. }
  136. this.network.MessageDispatcher.Dispatch(this, opcode, offset, messageBytes, (AMessage)message);
  137. }
  138. /// <summary>
  139. /// Rpc调用,发送一个消息,等待返回一个消息
  140. /// </summary>
  141. public Task<AResponse> Call(ARequest request)
  142. {
  143. request.RpcId = ++RpcId;
  144. var tcs = new TaskCompletionSource<AResponse>();
  145. this.requestCallback[request.RpcId] = (message) =>
  146. {
  147. try
  148. {
  149. AResponse response = (AResponse)message;
  150. if (response.Error > 100)
  151. {
  152. tcs.SetException(new RpcException(response.Error, response.Message));
  153. return;
  154. }
  155. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  156. tcs.SetResult(response);
  157. }
  158. catch (Exception e)
  159. {
  160. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  161. }
  162. };
  163. this.SendMessage(request);
  164. return tcs.Task;
  165. }
  166. /// <summary>
  167. /// Rpc调用
  168. /// </summary>
  169. public Task<AResponse> Call(ARequest request, CancellationToken cancellationToken)
  170. {
  171. request.RpcId = ++RpcId;
  172. var tcs = new TaskCompletionSource<AResponse>();
  173. this.requestCallback[request.RpcId] = (message) =>
  174. {
  175. try
  176. {
  177. AResponse response = (AResponse)message;
  178. if (response.Error > 100)
  179. {
  180. tcs.SetException(new RpcException(response.Error, response.Message));
  181. return;
  182. }
  183. //Log.Debug($"recv: {MongoHelper.ToJson(response)}");
  184. tcs.SetResult(response);
  185. }
  186. catch (Exception e)
  187. {
  188. tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
  189. }
  190. };
  191. cancellationToken.Register(() => { this.requestCallback.Remove(request.RpcId); });
  192. this.SendMessage(request);
  193. return tcs.Task;
  194. }
  195. public void Send(AMessage message)
  196. {
  197. if (this.Id == 0)
  198. {
  199. throw new Exception("session已经被Dispose了");
  200. }
  201. this.SendMessage(message);
  202. }
  203. public void Reply<Response>(Response message) where Response : AResponse
  204. {
  205. if (this.Id == 0)
  206. {
  207. throw new Exception("session已经被Dispose了");
  208. }
  209. this.SendMessage(message);
  210. }
  211. private void SendMessage(object message)
  212. {
  213. //Log.Debug($"send: {MongoHelper.ToJson(message)}");
  214. ushort opcode = this.network.Parent.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
  215. byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
  216. #if SERVER
  217. // 如果是allserver,内部消息不走网络,直接转给session,方便调试时看到整体堆栈
  218. if (this.network.AppType == AppType.AllServer)
  219. {
  220. Session session = this.network.Parent.GetComponent<NetInnerComponent>().Get(this.RemoteAddress);
  221. session.RunDecompressedBytes(opcode, messageBytes, 0, messageBytes.Length);
  222. return;
  223. }
  224. #endif
  225. byte[] opcodeBytes = BitConverter.GetBytes(opcode);
  226. this.byteses[0] = opcodeBytes;
  227. this.byteses[1] = messageBytes;
  228. channel.Send(this.byteses);
  229. }
  230. }
  231. }