AdvancedFileServer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net;
  7. using System.Threading;
  8. using System.IO;
  9. using System.Security.Cryptography;
  10. using System.Drawing;
  11. using HslCommunication.BasicFramework;
  12. using HslCommunication.LogNet;
  13. using HslCommunication.Core;
  14. namespace HslCommunication.Enthernet
  15. {
  16. /// <summary>
  17. /// 文件管理类服务器,负责服务器所有分类文件的管理,特点是不支持文件附加数据,但是支持直接访问文件名
  18. /// </summary>
  19. public class AdvancedFileServer : HslCommunication.Core.Net.NetworkFileServerBase
  20. {
  21. #region Constructor
  22. /// <summary>
  23. /// 实例化一个对象
  24. /// </summary>
  25. public AdvancedFileServer( )
  26. {
  27. }
  28. #endregion
  29. #region Override Method
  30. /// <summary>
  31. /// 处理数据
  32. /// </summary>
  33. /// <param name="obj"></param>
  34. protected override void ThreadPoolLogin( object obj )
  35. {
  36. if (obj is Socket)
  37. {
  38. Socket socket = (Socket)obj;
  39. OperateResult result = new OperateResult( );
  40. // 获取ip地址
  41. string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( );
  42. // 接收操作信息
  43. int customer;
  44. string fileName;
  45. string Factory;
  46. string Group;
  47. string Identify;
  48. OperateResult infoResult = ReceiveInformationHead(
  49. socket,
  50. out customer,
  51. out fileName,
  52. out Factory,
  53. out Group,
  54. out Identify );
  55. if (!infoResult.IsSuccess)
  56. {
  57. Console.WriteLine( infoResult.ToMessageShowString( ) );
  58. return;
  59. }
  60. string relativeName = ReturnRelativeFileName( Factory, Group, Identify, fileName );
  61. // 操作分流
  62. if (customer == HslProtocol.ProtocolFileDownload)
  63. {
  64. string fullFileName = ReturnAbsoluteFileName( Factory, Group, Identify, fileName );
  65. // 发送文件数据
  66. OperateResult sendFile = SendFileAndCheckReceive( socket, fullFileName, fileName, "", "" );
  67. if (!sendFile.IsSuccess)
  68. {
  69. LogNet?.WriteError( ToString( ), $"{StringResources.FileDownloadFailed}:{relativeName} ip:{IpAddress} 原因:{sendFile.Message}" );
  70. return;
  71. }
  72. else
  73. {
  74. socket?.Close( );
  75. LogNet?.WriteInfo( ToString( ), StringResources.FileDownloadSuccess + ":" + relativeName );
  76. }
  77. }
  78. else if (customer == HslProtocol.ProtocolFileUpload)
  79. {
  80. string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName( );
  81. string fullFileName = ReturnAbsoluteFileName( Factory, Group, Identify, fileName );
  82. // 上传文件
  83. CheckFolderAndCreate( );
  84. // 创建新的文件夹
  85. try
  86. {
  87. FileInfo info = new FileInfo( fullFileName );
  88. if (!Directory.Exists( info.DirectoryName ))
  89. {
  90. Directory.CreateDirectory( info.DirectoryName );
  91. }
  92. }
  93. catch (Exception ex)
  94. {
  95. LogNet?.WriteException( ToString( ), "创建文件夹失败:" + fullFileName, ex );
  96. socket?.Close( );
  97. return;
  98. }
  99. string FileName; // 文件名称,从客户端上传到服务器时,为上传人
  100. long FileSize;
  101. string FileTag;
  102. string FileUpload;
  103. OperateResult receiveFile = ReceiveFileFromSocketAndMoveFile(
  104. socket, // 网络套接字
  105. tempFileName, // 临时保存文件路径
  106. fullFileName, // 最终保存文件路径
  107. out FileName, // 文件名称,从客户端上传到服务器时,为上传人
  108. out FileSize,
  109. out FileTag,
  110. out FileUpload
  111. );
  112. if (receiveFile.IsSuccess)
  113. {
  114. socket?.Close( );
  115. LogNet?.WriteInfo( ToString( ), StringResources.FileUploadSuccess + ":" + relativeName );
  116. }
  117. else
  118. {
  119. LogNet?.WriteInfo( ToString( ), StringResources.FileUploadFailed + ":" + relativeName + " 原因:" + receiveFile.Message );
  120. }
  121. }
  122. else if (customer == HslProtocol.ProtocolFileDelete)
  123. {
  124. string fullFileName = ReturnAbsoluteFileName( Factory, Group, Identify, fileName );
  125. bool deleteResult = DeleteFileByName( fullFileName );
  126. // 回发消息
  127. if (SendStringAndCheckReceive(
  128. socket, // 网络套接字
  129. deleteResult ? 1 : 0, // 是否移动成功
  130. deleteResult ? "成功" : "失败" // 字符串数据
  131. ).IsSuccess)
  132. {
  133. socket?.Close( );
  134. }
  135. if (deleteResult) LogNet?.WriteInfo( ToString( ), StringResources.FileDeleteSuccess + ":" + relativeName );
  136. }
  137. else if (customer == HslProtocol.ProtocolFileDirectoryFiles)
  138. {
  139. List<GroupFileItem> fileNames = new List<GroupFileItem>( );
  140. foreach (var m in GetDirectoryFiles( Factory, Group, Identify ))
  141. {
  142. FileInfo fileInfo = new FileInfo( m );
  143. fileNames.Add( new GroupFileItem( )
  144. {
  145. FileName = fileInfo.Name,
  146. FileSize = fileInfo.Length,
  147. } );
  148. }
  149. Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject( fileNames.ToArray( ) );
  150. if (SendStringAndCheckReceive(
  151. socket,
  152. HslProtocol.ProtocolFileDirectoryFiles,
  153. jArray.ToString( )).IsSuccess)
  154. {
  155. socket?.Close( );
  156. }
  157. }
  158. else if (customer == HslProtocol.ProtocolFileDirectories)
  159. {
  160. List<string> folders = new List<string>( );
  161. foreach (var m in GetDirectories( Factory, Group, Identify ))
  162. {
  163. DirectoryInfo directory = new DirectoryInfo( m );
  164. folders.Add( directory.Name );
  165. }
  166. Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject( folders.ToArray( ) );
  167. if (SendStringAndCheckReceive(
  168. socket,
  169. HslProtocol.ProtocolFileDirectoryFiles,
  170. jArray.ToString( ) ).IsSuccess)
  171. {
  172. socket?.Close( );
  173. }
  174. }
  175. else
  176. {
  177. socket?.Close( );
  178. }
  179. }
  180. }
  181. /// <summary>
  182. /// 初始化数据
  183. /// </summary>
  184. protected override void StartInitialization( )
  185. {
  186. if (string.IsNullOrEmpty( FilesDirectoryPathTemp ))
  187. {
  188. throw new ArgumentNullException( "FilesDirectoryPathTemp", "No saved path is specified" );
  189. }
  190. base.StartInitialization( );
  191. }
  192. /// <summary>
  193. /// 检查文件夹
  194. /// </summary>
  195. protected override void CheckFolderAndCreate( )
  196. {
  197. if (!Directory.Exists( FilesDirectoryPathTemp ))
  198. {
  199. Directory.CreateDirectory( FilesDirectoryPathTemp );
  200. }
  201. base.CheckFolderAndCreate( );
  202. }
  203. /// <summary>
  204. /// 从网络套接字接收文件并移动到目标的文件夹中,如果结果异常,则结束通讯
  205. /// </summary>
  206. /// <param name="socket"></param>
  207. /// <param name="savename"></param>
  208. /// <param name="fileNameNew"></param>
  209. /// <param name="filename"></param>
  210. /// <param name="size"></param>
  211. /// <param name="filetag"></param>
  212. /// <param name="fileupload"></param>
  213. /// <returns></returns>
  214. private OperateResult ReceiveFileFromSocketAndMoveFile(
  215. Socket socket,
  216. string savename,
  217. string fileNameNew,
  218. out string filename,
  219. out long size,
  220. out string filetag,
  221. out string fileupload
  222. )
  223. {
  224. // 先接收文件
  225. OperateResult<FileBaseInfo> fileInfo = ReceiveFileFromSocket( socket, savename, null );
  226. if (!fileInfo.IsSuccess)
  227. {
  228. DeleteFileByName( savename );
  229. filename = null;
  230. size = 0;
  231. filetag = null;
  232. fileupload = null;
  233. return fileInfo;
  234. }
  235. filename = fileInfo.Content.Name;
  236. size = fileInfo.Content.Size;
  237. filetag = fileInfo.Content.Tag;
  238. fileupload = fileInfo.Content.Upload;
  239. // 标记移动文件,失败尝试三次
  240. int customer = 0;
  241. int times = 0;
  242. while (times < 3)
  243. {
  244. times++;
  245. if (MoveFileToNewFile( savename, fileNameNew ))
  246. {
  247. customer = 1;
  248. break;
  249. }
  250. else
  251. {
  252. Thread.Sleep( 500 );
  253. }
  254. }
  255. if (customer == 0)
  256. {
  257. DeleteFileByName( savename );
  258. }
  259. // 回发消息
  260. OperateResult sendString = SendStringAndCheckReceive( socket, customer, "success" );
  261. return sendString;
  262. }
  263. #endregion
  264. #region Public Method
  265. /// <summary>
  266. /// 用于接收上传文件时的临时文件夹,临时文件使用结束后会被删除
  267. /// </summary>
  268. public string FilesDirectoryPathTemp
  269. {
  270. get { return m_FilesDirectoryPathTemp; }
  271. set { m_FilesDirectoryPathTemp = PreprocessFolderName( value ); }
  272. }
  273. #endregion
  274. #region Private Member
  275. private string m_FilesDirectoryPathTemp = null;
  276. #endregion
  277. #region Object Override
  278. /// <summary>
  279. /// 获取本对象的字符串标识形式
  280. /// </summary>
  281. /// <returns></returns>
  282. public override string ToString()
  283. {
  284. return "AdvancedFileServer";
  285. }
  286. #endregion
  287. }
  288. }