Session.cs 7.8 KB
Newer Older
1 2 3 4 5
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

6
namespace Model
7
{
8
	public sealed class Session : Entity
9
	{
10
		private static uint RpcId { get; set; }
11
		private readonly NetworkComponent network;
12
		private readonly Dictionary<uint, Action<object>> requestCallback = new Dictionary<uint, Action<object>>();
13
		private readonly AChannel channel;
14
		private readonly List<byte[]> byteses = new List<byte[]>() {new byte[0], new byte[0]};
15

16
		public Session(NetworkComponent network, AChannel channel)
17
		{
18
			this.network = network;
19
			this.channel = channel;
T
tanghai 已提交
20 21 22 23 24 25 26 27 28
			this.StartRecv();
		}

		public string RemoteAddress
		{
			get
			{
				return this.channel.RemoteAddress;
			}
29
		}
30

31 32 33 34 35 36 37 38
		public ChannelType ChannelType
		{
			get
			{
				return this.channel.ChannelType;
			}
		}

T
tanghai 已提交
39
		private async void StartRecv()
40 41 42
		{
			while (true)
			{
T
tanghai 已提交
43 44 45 46 47
				if (this.Id == 0)
				{
					return;
				}

48 49 50
				byte[] messageBytes;
				try
				{
51 52
					messageBytes = await channel.Recv();
					if (this.Id == 0)
53
					{
54
						return;
55
					}
56 57 58 59 60 61 62
				}
				catch (Exception e)
				{
					Log.Error(e.ToString());
					continue;
				}

63
				if (messageBytes.Length < 3)
64
				{
65 66 67
					Log.Error($"message error length < 3, ip: {this.RemoteAddress}");
					this.network.Remove(this.Id);
					return;
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
				}

				ushort opcode = BitConverter.ToUInt16(messageBytes, 0);
				try
				{
					this.Run(opcode, messageBytes);
				}
				catch (Exception e)
				{
					Log.Error(e.ToString());
				}
			}
		}

		private void Run(ushort opcode, byte[] messageBytes)
		{
			int offset = 0;
85 86
			// opcode最高位表示是否压缩
			bool isCompressed = (opcode & 0x8000) > 0;
87
			if (isCompressed) // 最高位为1,表示有压缩,需要解压缩
88
			{
89
				messageBytes = ZipHelper.Decompress(messageBytes, 2, messageBytes.Length - 2);
90 91 92 93
				offset = 0;
			}
			else
			{
94
				offset = 2;
95
			}
96
			opcode &= 0x7fff;
97
			this.RunDecompressedBytes(opcode, messageBytes, offset);
98 99
		}

100
		private void RunDecompressedBytes(ushort opcode, byte[] messageBytes, int offset)
101
		{
102
			object message;
T
tanghai 已提交
103
			Opcode op;
104 105 106

			try
			{
T
tanghai 已提交
107
				op = (Opcode)opcode;
108 109 110 111 112
				Type messageType = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetType(op);
				message = this.network.MessagePacker.DeserializeFrom(messageType, messageBytes, offset, messageBytes.Length - offset);
			}
			catch (Exception e)
			{
T
tanghai 已提交
113
				Log.Error($"message deserialize error, ip: {this.RemoteAddress} {opcode} {e}");
114 115 116
				this.network.Remove(this.Id);
				return;
			}
117

T
tanghai 已提交
118
			//Log.Debug($"recv: {MongoHelper.ToJson(message)}");
T
tanghai 已提交
119

120 121
			AResponse response = message as AResponse;
			if (response != null)
122
			{
123 124 125 126 127 128 129 130 131
				// rpcFlag>0 表示这是一个rpc响应消息
				// Rpc回调有找不着的可能,因为client可能取消Rpc调用
				Action<object> action;
				if (!this.requestCallback.TryGetValue(response.RpcId, out action))
				{
					return;
				}
				this.requestCallback.Remove(response.RpcId);
				action(message);
132
				return;
133
			}
134

T
tanghai 已提交
135
			this.network.MessageDispatcher.Dispatch(this, op, offset, messageBytes, (AMessage)message);
136
		}
T
tanghai 已提交
137 138 139 140
		
		/// <summary>
		/// Rpc调用
		/// </summary>
141
		public void CallWithAction(ARequest request, Action<AResponse> action)
T
tanghai 已提交
142 143 144 145 146 147 148 149 150
		{
			request.RpcId = ++RpcId;
			this.SendMessage(request);

			this.requestCallback[RpcId] = (message) =>
			{
				try
				{
					AResponse response = (AResponse)message;
151
					action(response);
T
tanghai 已提交
152 153 154
				}
				catch (Exception e)
				{
155
					Log.Error(e.ToString());
156 157 158 159
				}
			};
		}

T
tanghai 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
		/// <summary>
		/// Rpc调用,发送一个消息,等待返回一个消息
		/// </summary>
		public Task<AResponse> Call(ARequest request, bool isHotfix)
		{
			request.RpcId = ++RpcId;
			this.SendMessage(request);

			var tcs = new TaskCompletionSource<AResponse>();
			this.requestCallback[RpcId] = (message) =>
			{
				try
				{
					AResponse response = (AResponse)message;
					if (response.Error > 100)
					{
						tcs.SetException(new RpcException(response.Error, response.Message));
						return;
					}
					//Log.Debug($"recv: {MongoHelper.ToJson(response)}");
					tcs.SetResult(response);
				}
				catch (Exception e)
				{
					tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
				}
			};

			return tcs.Task;
		}

		/// <summary>
		/// Rpc调用
		/// </summary>
		public Task<AResponse> Call(ARequest request, bool isHotfix, CancellationToken cancellationToken)
		{
			request.RpcId = ++RpcId;
			this.SendMessage(request);

			var tcs = new TaskCompletionSource<AResponse>();

			this.requestCallback[RpcId] = (message) =>
			{
				try
				{
					AResponse response = (AResponse)message;
					if (response.Error > 100)
					{
						tcs.SetException(new RpcException(response.Error, response.Message));
						return;
					}
					//Log.Debug($"recv: {MongoHelper.ToJson(response)}");
					tcs.SetResult(response);
				}
				catch (Exception e)
				{
					tcs.SetException(new Exception($"Rpc Error: {message.GetType().FullName}", e));
				}
			};

			cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });

			return tcs.Task;
		}

225 226 227
		/// <summary>
		/// Rpc调用,发送一个消息,等待返回一个消息
		/// </summary>
228
		public Task<Response> Call<Response>(ARequest request) where Response : AResponse
229
		{
230 231
			request.RpcId = ++RpcId;
			this.SendMessage(request);
232

233
			var tcs = new TaskCompletionSource<Response>();
234
			this.requestCallback[RpcId] = (message) =>
235 236 237
			{
				try
				{
238
					Response response = (Response)message;
239
					if (response.Error > 100)
240
					{
241
						tcs.SetException(new RpcException(response.Error, response.Message));
242 243
						return;
					}
T
tanghai 已提交
244
					//Log.Debug($"recv: {MongoHelper.ToJson(response)}");
245 246 247 248
					tcs.SetResult(response);
				}
				catch (Exception e)
				{
249
					tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
250 251
				}
			};
252

253 254 255
			return tcs.Task;
		}

T
tanghai 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
		/// <summary>
		/// Rpc调用
		/// </summary>
		public Task<Response> Call<Response>(ARequest request, CancellationToken cancellationToken)
			where Response : AResponse
		{
			request.RpcId = ++RpcId;
			this.SendMessage(request);

			var tcs = new TaskCompletionSource<Response>();

			this.requestCallback[RpcId] = (message) =>
			{
				try
				{
					Response response = (Response)message;
					if (response.Error > 100)
					{
						tcs.SetException(new RpcException(response.Error, response.Message));
						return;
					}
					//Log.Debug($"recv: {MongoHelper.ToJson(response)}");
					tcs.SetResult(response);
				}
				catch (Exception e)
				{
					tcs.SetException(new Exception($"Rpc Error: {typeof(Response).FullName}", e));
				}
			};

			cancellationToken.Register(() => { this.requestCallback.Remove(RpcId); });

			return tcs.Task;
		}

291
		public void Send(AMessage message)
292
		{
T
tanghai 已提交
293 294 295 296
			if (this.Id == 0)
			{
				throw new Exception("session已经被Dispose了");
			}
297
			this.SendMessage(message);
298 299
		}

300
		public void Reply<Response>(Response message) where Response : AResponse
301
		{
T
tanghai 已提交
302 303 304 305
			if (this.Id == 0)
			{
				throw new Exception("session已经被Dispose了");
			}
306
			this.SendMessage(message);
307 308
		}

309
		private void SendMessage(object message)
310
		{
T
tanghai 已提交
311
			//Log.Debug($"send: {MongoHelper.ToJson(message)}");
T
tanghai 已提交
312 313
			Opcode opcode = this.network.Entity.GetComponent<OpcodeTypeComponent>().GetOpcode(message.GetType());
			ushort op = (ushort)opcode;
314
			byte[] messageBytes = this.network.MessagePacker.SerializeToByteArray(message);
315
			if (messageBytes.Length > 100)
316
			{
317 318 319 320
				byte[] newMessageBytes = ZipHelper.Compress(messageBytes);
				if (newMessageBytes.Length < messageBytes.Length)
				{
					messageBytes = newMessageBytes;
T
tanghai 已提交
321
					op |= 0x8000;
322
				}
323 324
			}

T
tanghai 已提交
325
			byte[] opcodeBytes = BitConverter.GetBytes(op);
326 327 328 329
			
			this.byteses[0] = opcodeBytes;
			this.byteses[1] = messageBytes;
			channel.Send(this.byteses);
330 331 332 333 334 335 336 337 338
		}

		public override void Dispose()
		{
			if (this.Id == 0)
			{
				return;
			}

339 340
			long id = this.Id;

341
			base.Dispose();
T
tanghai 已提交
342

T
tanghai 已提交
343
			this.channel.Dispose();
344
			this.network.Remove(id);
345 346 347
		}
	}
}