P1Server.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. using LJLib.D;
  2. using LJLib.Net.SPI.Com;
  3. using LJLib.Net.SPI.Server;
  4. using LJLib.Text.Parser;
  5. using LJLib.Tools.Helper;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.IO.Compression;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. using System.Threading;
  14. namespace LJLib.TcpHandle
  15. {
  16. internal class P1Server : TcpHandler, IRemoteInfoContainer
  17. {
  18. private ILJServer _server = null;
  19. private const byte NEW_ALLGZIP = 0x10;
  20. private const byte SVRBEAT = 0x08;
  21. private const byte PROTOCOL_FLAG = 0x04;
  22. private const byte READ_GZIP = 0x02;
  23. private const byte WRITE_GZIP = 0x01;
  24. private const int JsonMaxLen = 0x14000000;
  25. private const int FileNameMaxLen = 0x01400000;
  26. private const int FileMaxLen = 0x28000000;
  27. private byte headByte = 0x00;
  28. private string apiName = string.Empty;
  29. private LJParser parser = new LJParser();
  30. public P1Server(TcpClient client, ILJServer server)
  31. : base(client)
  32. {
  33. _server = server;
  34. }
  35. protected override void DataArrived()
  36. {
  37. headByte = _reader.ReadByte();
  38. if (headByte == 0)
  39. {
  40. return;
  41. }
  42. if (headByte > 0x1F || (headByte & PROTOCOL_FLAG) != PROTOCOL_FLAG)
  43. {
  44. throw new Exception("不支持协议" + headByte.ToString("X2"));
  45. }
  46. if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
  47. {
  48. if ((headByte & READ_GZIP) != READ_GZIP)
  49. {
  50. throw new Exception("协议异常:新协议必须压缩发送");
  51. }
  52. if ((headByte & WRITE_GZIP) != WRITE_GZIP)
  53. {
  54. throw new Exception("协议异常:新协议必须压缩返回");
  55. }
  56. }
  57. DebugHelper.Start("ReadJsonStr");
  58. BinaryReader reader = null;
  59. GZipStream stream = null;
  60. MemoryStream ms = null;
  61. if ((headByte & READ_GZIP) == READ_GZIP)
  62. {
  63. if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
  64. {
  65. var allen = new byte[4];
  66. _ns.Read(allen, 0, allen.Length);
  67. var len = BitConverter.ToInt32(allen, 0);
  68. ms = new MemoryStream();
  69. StreamHelper.StreamCopy(ms, _ns, len);
  70. Debug.Write("ReadFromNet End");
  71. ms.Seek(0, SeekOrigin.Begin);
  72. stream = new GZipStream(ms, CompressionMode.Decompress, false);
  73. reader = new BinaryReader(stream);
  74. }
  75. else
  76. {
  77. stream = new GZipStream(_ns, CompressionMode.Decompress, true);
  78. reader = new BinaryReader(stream);
  79. }
  80. }
  81. else
  82. {
  83. reader = new BinaryReader(_ns);
  84. }
  85. bool hasRslt = false;
  86. object syncRoot = new object();
  87. Timer timer = null;
  88. if ((headByte & SVRBEAT) == SVRBEAT)
  89. {
  90. timer = new Timer(state =>
  91. {
  92. if (hasRslt)
  93. {
  94. timer.Dispose();
  95. return;
  96. }
  97. lock (syncRoot)
  98. {
  99. if (!hasRslt)
  100. {
  101. try
  102. {
  103. _writer.Write(false);
  104. }
  105. catch (Exception)
  106. {
  107. }
  108. }
  109. }
  110. }, null, 3000, 3000);
  111. }
  112. using (ms)
  113. using (stream)
  114. using (timer)
  115. try
  116. {
  117. var len = reader.ReadInt32();
  118. if (len > JsonMaxLen)
  119. {
  120. throw new Exception(string.Format("请求Json字符串长度不能大于{0:#,##0.##}M", (double)JsonMaxLen / 1024 / 1024));
  121. }
  122. if (len <= 0)
  123. {
  124. throw new Exception("Json字符串长度不能小于等于0");
  125. }
  126. var str = Encoding.UTF8.GetString(reader.ReadBytes(len));
  127. DebugHelper.Stop("ReadJsonStr");
  128. var index = str.IndexOf('{');
  129. if (index <= 0)
  130. {
  131. throw new Exception("协议错误");
  132. }
  133. apiName = str.Substring(0, index);
  134. var body = str.Substring(index);
  135. Debug.Write(string.Format("Request:{0}:{1}", apiName, body));
  136. DebugHelper.Start("ReadRequestFiles_" + apiName);
  137. Type requestType = _server.GetRequestType(apiName);
  138. Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();
  139. var filecnt = reader.ReadInt16();
  140. if (filecnt < 0)
  141. {
  142. throw new Exception("文件数不能小于0");
  143. }
  144. if (filecnt > 1000)
  145. {
  146. throw new Exception("文件数不能大于1000");
  147. }
  148. for (int i = 0; i < filecnt; i++)
  149. {
  150. var strlen = reader.ReadInt32();
  151. if (strlen > FileNameMaxLen)
  152. {
  153. throw new Exception(string.Format("文件名长度不能大于{0:#,##0.##}M", (double)FileNameMaxLen / 1024 / 1024));
  154. }
  155. if (strlen <= 0)
  156. {
  157. throw new Exception("文件名长度不能小于等于0");
  158. }
  159. var filename = Encoding.UTF8.GetString(reader.ReadBytes(strlen));
  160. var filelen = reader.ReadInt32();
  161. if (filelen > FileMaxLen)
  162. {
  163. throw new Exception(string.Format("文件大小不能大于{0:#,##0.##}M", (double)FileMaxLen / 1024 / 1024));
  164. }
  165. if (filelen <= 0)
  166. {
  167. throw new Exception("文件大小不能小于等于0");
  168. }
  169. var filedata = reader.ReadBytes(filelen);
  170. files.Add(filename, filedata);
  171. }
  172. if (stream != null)
  173. {
  174. stream.Close();
  175. }
  176. DebugHelper.Stop("ReadRequestFiles_" + apiName);
  177. DebugHelper.Start("JsonToRequest_" + apiName);
  178. ILJRequest request = parser.JsonParse(requestType, body, files) as ILJRequest;
  179. DebugHelper.Stop("JsonToRequest_" + apiName);
  180. DebugHelper.Start("DoExcute_" + apiName);
  181. LJResponse rslt = null;
  182. try
  183. {
  184. rslt = _server.DoExcute(request, this);
  185. if (!string.IsNullOrEmpty(rslt.ErrMsg))
  186. {
  187. Trace.Write(apiName + "返回错误信息:" + rslt.ErrMsg);
  188. }
  189. }
  190. catch (System.Exception ex)
  191. {
  192. Trace.Write(ex.ToString());
  193. rslt = new ErrResponse(ex.ToString());
  194. }
  195. DebugHelper.Stop("DoExcute_" + apiName);
  196. if ((headByte & SVRBEAT) == SVRBEAT)
  197. {
  198. lock (syncRoot)
  199. {
  200. hasRslt = true;
  201. _writer.Write(true);
  202. }
  203. }
  204. WriteResponse(headByte, rslt);
  205. }
  206. catch (Exception ex)
  207. {
  208. Trace.Write(ex.ToString());
  209. var errRsp = new ErrResponse { ErrCode = "exp", ErrMsg = ex.ToString() };
  210. if ((headByte & SVRBEAT) == SVRBEAT)
  211. {
  212. lock (syncRoot)
  213. {
  214. hasRslt = true;
  215. _writer.Write(true);
  216. }
  217. }
  218. WriteResponse(headByte, errRsp);
  219. throw;
  220. }
  221. }
  222. private void WriteResponse(byte headByte, LJResponse rslt)
  223. {
  224. DebugHelper.Start("ResponseToJson_" + apiName);
  225. BinaryWriter writer = null;
  226. GZipStream ostream = null;
  227. MemoryStream ms = null;
  228. if ((headByte & WRITE_GZIP) == WRITE_GZIP)
  229. {
  230. ms = new MemoryStream();
  231. writer = new BinaryWriter(ms);
  232. }
  233. else
  234. {
  235. writer = new BinaryWriter(_ns);
  236. }
  237. var ofiles = new Dictionary<string, byte[]>();
  238. var strrslt = parser.ToJson(rslt, ofiles);
  239. byte ofilecnt = 0;
  240. DebugHelper.Stop("ResponseToJson_" + apiName);
  241. Debug.Write("ResponseToJson End");
  242. if (ofiles.Count > byte.MaxValue)
  243. {
  244. DebugHelper.Start("返回文件数太多_" + apiName);
  245. var ErrMsg = "返回文件数太多,超过255个:" + ofiles.Count;
  246. Trace.Write(ErrMsg);
  247. ofiles.Clear();
  248. strrslt = parser.ToJson(new ErrResponse { ErrCode = "", ErrMsg = ErrMsg });
  249. ofilecnt = (byte)ofiles.Count;
  250. DebugHelper.Stop("返回文件数太多_" + apiName);
  251. }
  252. else
  253. {
  254. ofilecnt = (byte)ofiles.Count;
  255. }
  256. Debug.Write(strrslt);//把返回的东西写入log
  257. DebugHelper.Start("WriteResponseToMS_" + apiName);
  258. var rsltbytes = Encoding.UTF8.GetBytes(strrslt);
  259. writer.Write(rsltbytes.Length);
  260. writer.Write(rsltbytes);
  261. writer.Write(ofilecnt);
  262. writer.Flush();
  263. foreach (var file in ofiles)
  264. {
  265. var filenamebytes = Encoding.UTF8.GetBytes(file.Key);
  266. writer.Write(filenamebytes.Length);
  267. writer.Write(filenamebytes);
  268. writer.Write(file.Value.Length);
  269. writer.Write(file.Value);
  270. writer.Flush();
  271. }
  272. DebugHelper.Stop("WriteResponseToMS_" + apiName);
  273. Debug.Write("WriteResponseToMS End");
  274. if ((headByte & WRITE_GZIP) == WRITE_GZIP)
  275. {
  276. DebugHelper.Start("MS_To_GZip_" + apiName);
  277. var gzipms = NewGzipms(ms);
  278. // DONE: GZIP压缩是否有问题
  279. var L = gzipms.ReadByte();
  280. var magic = (gzipms.ReadByte() << 8) | L;
  281. if (magic != 0x8b1f)
  282. {
  283. DebugHelper.Start("FixGZipErr_" + apiName);
  284. gzipms.Dispose();
  285. gzipms = NewGzipms(ms);
  286. L = gzipms.ReadByte();
  287. magic = (gzipms.ReadByte() << 8) | L;
  288. if (magic != 0x8b1f)
  289. {
  290. Trace.Write("GZIPFormatErr:" + BitConverter.ToString(ms.ToArray()));
  291. }
  292. DebugHelper.Stop("FixGZipErr_" + apiName);
  293. }
  294. ms.Dispose();
  295. DebugHelper.Stop("MS_To_GZip_" + apiName);
  296. Debug.Write("MS_To_GZip End");
  297. if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
  298. {
  299. var allen = BitConverter.GetBytes((int)gzipms.Length);
  300. _ns.Write(allen, 0, allen.Length);
  301. Debug.Write("WriteLen End-" + gzipms.Length);
  302. }
  303. DebugHelper.Start("WriteGzipToNet_" + apiName);
  304. gzipms.Seek(0, SeekOrigin.Begin);
  305. StreamHelper.StreamCopy(_ns, gzipms);
  306. gzipms.Dispose();
  307. DebugHelper.Stop("WriteGzipToNet_" + apiName);
  308. Debug.Write("WriteGzipToNet End");
  309. }
  310. }
  311. private static MemoryStream NewGzipms(MemoryStream ms)
  312. {
  313. var gzipms = new MemoryStream();
  314. var gzipstream = new GZipStream(gzipms, CompressionMode.Compress, true);
  315. ms.Seek(0, SeekOrigin.Begin);
  316. StreamHelper.StreamCopy(gzipstream, ms);
  317. gzipstream.Dispose();
  318. gzipms.Seek(0, SeekOrigin.Begin);
  319. return gzipms;
  320. }
  321. public string RemoteInfo
  322. {
  323. get
  324. {
  325. try
  326. {
  327. return _client.Client.RemoteEndPoint.ToString();
  328. }
  329. catch (Exception ex)
  330. {
  331. Trace.Write(ex.ToString());
  332. return null;
  333. }
  334. }
  335. }
  336. }
  337. }