TCP_ProtocolHelperXML.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using LYFZ.Network.EnumerateLibrary;
  6. using System.Xml;
  7. namespace LYFZ.Network
  8. {
  9. /// <summary>
  10. /// ProtocolHelper辅助类
  11. ///这个类专用于将XML格式的协议映射为我们上面定义的强类型对象,这里我没有加入
  12. ///try/catch异常处理,因为协议对用户来说是不可见的,而且客户端应该总是发送正确的协议
  13. /// </summary>
  14. public class TCP_ProtocolHelperXML
  15. {
  16. private XmlNode fileNode;
  17. private XmlNode root;
  18. /// <summary>
  19. /// 初始化
  20. /// </summary>
  21. /// <param name="protocol">XML格式的协议字符串</param>
  22. public TCP_ProtocolHelperXML(string protocol)
  23. {
  24. if (protocol.Trim().Length > 1)
  25. {
  26. XmlDocument doc = new XmlDocument();
  27. doc.LoadXml(protocol);
  28. root = doc.DocumentElement;
  29. fileNode = root.SelectSingleNode("information");
  30. }
  31. }
  32. /// <summary>
  33. /// 获取TCP数据传送类型,是文字信息还是文件,此时的protocal一定为单条完整protocal
  34. /// </summary>
  35. /// <returns></returns>
  36. private InformationType GetInformationType()
  37. {
  38. string mode = fileNode.Attributes["Type"].Value;
  39. if (mode.ToLower() == "msg")
  40. {
  41. return InformationType.Message;
  42. }
  43. else if (mode.ToLower() == "file")
  44. {
  45. return InformationType.File;
  46. }
  47. else
  48. {
  49. return (InformationType)Enum.Parse(typeof(InformationType), mode);
  50. }
  51. }
  52. /// <summary>
  53. /// 获取单条协议包含的信息
  54. /// </summary>
  55. /// <returns></returns>
  56. public TCP_FileProtocol GetProtocol()
  57. {
  58. try
  59. {
  60. //Type=\"{0}\" ExtraInfo=\"{1}\" ReceiveFileSize=\"{2}\" ClientInfo=\"{3}\" ServerStartTimeStamp=\"{4}\"
  61. string ExtraInfo = "";
  62. long receiveFileSize = 0;
  63. InformationType infoType = GetInformationType();
  64. string content = "";
  65. ExtraInfo = LYFZ.WinAPI.SDKSecurity.Decode(fileNode.Attributes["ExtraInfo"].Value);
  66. try
  67. {
  68. receiveFileSize = Convert.ToInt64(fileNode.Attributes["ReceiveFileSize"].Value);
  69. }
  70. catch { }
  71. content = LYFZ.WinAPI.SDKSecurity.Decode(fileNode.InnerText.Trim());
  72. string clientInfo = "";
  73. string serverStartTimeStamp = "";
  74. try
  75. {
  76. clientInfo = fileNode.Attributes["ClientInfo"].Value;
  77. serverStartTimeStamp = fileNode.Attributes["ServerStartTimeStamp"].Value;
  78. }
  79. catch { }
  80. TCP_FileProtocol retProtocol= new TCP_FileProtocol(infoType, content, ExtraInfo, clientInfo);
  81. retProtocol.ServerStartTimeStamp = serverStartTimeStamp;
  82. retProtocol.ReceiveFileSize = receiveFileSize;
  83. return retProtocol;
  84. }
  85. catch { return new TCP_FileProtocol(); }
  86. }
  87. }
  88. }