TCP_ProtocolHandler.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace LYFZ.Network
  6. {
  7. /// <summary>
  8. /// 处理协议的ProtocalHandler处理类
  9. /// </summary>
  10. public class TCP_ProtocolHandler
  11. {
  12. private string partialProtocol; // 保存不完整的协议
  13. public TCP_ProtocolHandler()
  14. {
  15. partialProtocol = "";
  16. }
  17. public string[] GetProtocol(string input)
  18. {
  19. return GetProtocol(input, null);
  20. }
  21. /// <summary>
  22. /// 获得协议
  23. /// </summary>
  24. /// <param name="input"></param>
  25. /// <param name="outputList"></param>
  26. /// <returns></returns>
  27. private string[] GetProtocol(string input, List<string> outputList)
  28. {
  29. if (outputList == null)
  30. outputList = new List<string>();
  31. if (String.IsNullOrEmpty(input))
  32. return outputList.ToArray();
  33. if (!String.IsNullOrEmpty(partialProtocol))
  34. input = partialProtocol + input;
  35. string pattern = "(^<lyfz_protocol>.*?</lyfz_protocol>)";
  36. HPSocketCS.Extended.SystemFileLogs.WriteLogs("匹配协议:" + input);
  37. // 如果有匹配,说明已经找到了,是完整的协议
  38. if (Regex.IsMatch(input, pattern))
  39. {
  40. // 获取匹配的值
  41. string match = Regex.Match(input, pattern).Groups[0].Value;
  42. outputList.Add(match);
  43. partialProtocol = "";
  44. // 缩短input的长度
  45. input = input.Substring(match.Length);
  46. // 递归调用
  47. GetProtocol(input, outputList);
  48. }
  49. else
  50. {
  51. // 如果不匹配,说明协议的长度不够,
  52. // 那么先缓存,然后等待下一次请求
  53. partialProtocol = input;
  54. }
  55. return outputList.ToArray();
  56. }
  57. /// <summary>
  58. /// 获得协议
  59. /// </summary>
  60. /// <param name="input"></param>
  61. /// <returns></returns>
  62. public string GetProtocolInfo(string input)
  63. {
  64. string pattern = "(^<lyfz_protocol>.*?</lyfz_protocol>)";
  65. // 如果有匹配,说明已经找到了,是完整的协议
  66. if (Regex.IsMatch(input, pattern))
  67. {
  68. // LYFZ.BLL.BLL_FileLogs.WriteMainLogs("匹配协议成功");
  69. // 获取匹配的值
  70. string match = Regex.Match(input, pattern).Groups[0].Value;
  71. return match;
  72. }
  73. else
  74. {
  75. // 如果不匹配,说明协议的长度不够,
  76. // 那么先缓存,然后等待下一次请求
  77. return "";
  78. }
  79. }
  80. }
  81. }