UltimateFileServer.cs
11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using HslCommunication.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace HslCommunication.Enthernet
{
/// <summary>
/// 终极文件管理服务器,实现所有的文件分类管理,读写分离,不支持直接访问文件名
/// </summary>
/// <remarks>
/// 本文件的服务器支持存储文件携带的额外信息,文件名被映射成了新的名称,无法在服务器直接查看文件信息。
/// </remarks>
/// <example>
/// 以下的示例来自Demo项目,创建了一个简单的服务器对象。
/// <code lang="cs" source="TestProject\FileNetServer\FormFileServer.cs" region="Ultimate Server" title="UltimateFileServer示例" />
/// </example>
public class UltimateFileServer : Core.Net.NetworkFileServerBase
{
#region Constructor
/// <summary>
/// 实例化一个对象
/// </summary>
public UltimateFileServer()
{
}
#endregion
#region File list Container
/// <summary>
/// 所有文件组操作的词典锁
/// </summary>
internal Dictionary<string, GroupFileContainer> m_dictionary_group_marks = new Dictionary<string, GroupFileContainer>();
/// <summary>
/// 词典的锁
/// </summary>
private SimpleHybirdLock hybirdLock = new SimpleHybirdLock();
/// <summary>
/// 获取当前目录的读写锁,如果没有会自动创建
/// </summary>
/// <param name="filePath">相对路径名</param>
/// <returns>读写锁</returns>
public GroupFileContainer GetGroupFromFilePath(string filePath)
{
GroupFileContainer GroupFile = null;
hybirdLock.Enter();
// lock operator
if (m_dictionary_group_marks.ContainsKey(filePath))
{
GroupFile = m_dictionary_group_marks[filePath];
}
else
{
GroupFile = new GroupFileContainer(LogNet, filePath);
m_dictionary_group_marks.Add(filePath, GroupFile);
}
hybirdLock.Leave();
return GroupFile;
}
#endregion
#region Receive File And Updata List
/// <summary>
/// 从套接字接收文件并保存,更新文件列表
/// </summary>
/// <param name="socket">套接字</param>
/// <param name="savename">保存的文件名</param>
/// <returns>是否成功的结果对象</returns>
private OperateResult ReceiveFileFromSocketAndUpdateGroup(
Socket socket,
string savename
)
{
FileInfo info = new FileInfo(savename);
string guidName = CreateRandomFileName();
string fileName = info.DirectoryName + "\\" + guidName;
OperateResult<FileBaseInfo> receive = ReceiveFileFromSocket(socket, fileName, null);
if (!receive.IsSuccess)
{
DeleteFileByName(fileName);
return receive;
}
// 更新操作
GroupFileContainer fileManagment = GetGroupFromFilePath(info.DirectoryName);
string oldName = fileManagment.UpdateFileMappingName(
info.Name,
receive.Content.Size,
guidName,
receive.Content.Upload,
receive.Content.Tag
);
// 删除旧的文件
DeleteExsistingFile(info.DirectoryName, oldName);
// 回发消息
return SendStringAndCheckReceive(socket, 1, StringResources.Language.SuccessText);
}
#endregion
#region Private Method
/// <summary>
/// 根据文件的显示名称转化为真实存储的名称
/// </summary>
/// <param name="factory">第一大类</param>
/// <param name="group">第二大类</param>
/// <param name="id">第三大类</param>
/// <param name="fileName">文件显示名称</param>
/// <returns>是否成功的结果对象</returns>
private string TransformFactFileName(string factory, string group, string id, string fileName)
{
string path = ReturnAbsoluteFilePath(factory, group, id);
GroupFileContainer fileManagment = GetGroupFromFilePath(path);
return fileManagment.GetCurrentFileMappingName(fileName);
}
/// <summary>
/// 删除已经存在的文件信息
/// </summary>
/// <param name="path">文件的路径</param>
/// <param name="fileName">文件的名称</param>
private void DeleteExsistingFile(string path, string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
string fileUltimatePath = path + "\\" + fileName;
FileMarkId fileMarkId = GetFileMarksFromDictionaryWithFileName(fileName);
fileMarkId.AddOperation(() =>
{
if (!DeleteFileByName(fileUltimatePath))
{
LogNet?.WriteInfo(ToString(), StringResources.Language.FileDeleteFailed + fileUltimatePath);
}
});
}
}
#endregion
#region Protect Override
/// <summary>
/// 当接收到了新的请求的时候执行的操作
/// </summary>
/// <param name="socket">异步对象</param>
/// <param name="endPoint">终结点</param>
protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint)
{
OperateResult result = new OperateResult();
// 获取ip地址
string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString();
// 接收操作信息
if (!ReceiveInformationHead(
socket,
out int customer,
out string fileName,
out string Factory,
out string Group,
out string Identify).IsSuccess)
{
return;
}
string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName);
if (customer == HslProtocol.ProtocolFileDownload)
{
// 先获取文件的真实名称
string guidName = TransformFactFileName(Factory, Group, Identify, fileName);
// 获取文件操作锁
FileMarkId fileMarkId = GetFileMarksFromDictionaryWithFileName(guidName);
fileMarkId.EnterReadOperator();
// 发送文件数据
OperateResult send = SendFileAndCheckReceive(socket, ReturnAbsoluteFileName(Factory, Group, Identify, guidName), fileName, "", "", null);
if (!send.IsSuccess)
{
fileMarkId.LeaveReadOperator();
LogNet?.WriteError(ToString(), $"{StringResources.Language.FileDownloadFailed} : {send.Message} :{relativeName} ip:{IpAddress}");
return;
}
else
{
LogNet?.WriteInfo(ToString(), StringResources.Language.FileDownloadSuccess + ":" + relativeName);
}
fileMarkId.LeaveReadOperator();
// 关闭连接
socket?.Close();
}
else if (customer == HslProtocol.ProtocolFileUpload)
{
string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);
// 上传文件
CheckFolderAndCreate();
FileInfo info = new FileInfo(fullFileName);
try
{
if (!Directory.Exists(info.DirectoryName))
{
Directory.CreateDirectory(info.DirectoryName);
}
}
catch (Exception ex)
{
LogNet?.WriteException(ToString(), StringResources.Language.FilePathCreateFailed + fullFileName, ex);
socket?.Close();
return;
}
// 接收文件并回发消息
if (ReceiveFileFromSocketAndUpdateGroup(
socket, // 网络套接字
fullFileName).IsSuccess)
{
socket?.Close();
LogNet?.WriteInfo(ToString(), StringResources.Language.FileUploadSuccess + ":" + relativeName);
}
else
{
LogNet?.WriteInfo(ToString(), StringResources.Language.FileUploadFailed + ":" + relativeName);
}
}
else if (customer == HslProtocol.ProtocolFileDelete)
{
string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName);
FileInfo info = new FileInfo(fullFileName);
GroupFileContainer fileManagment = GetGroupFromFilePath(info.DirectoryName);
// 新增删除的任务
DeleteExsistingFile(info.DirectoryName, fileManagment.DeleteFile(info.Name));
// 回发消息
if (SendStringAndCheckReceive(
socket, // 网络套接字
1, // 没啥含义
"success" // 没啥含意
).IsSuccess)
{
socket?.Close();
}
LogNet?.WriteInfo(ToString(), StringResources.Language.FileDeleteSuccess + ":" + relativeName);
}
else if (customer == HslProtocol.ProtocolFileDirectoryFiles)
{
GroupFileContainer fileManagment = GetGroupFromFilePath(ReturnAbsoluteFilePath(Factory, Group, Identify));
if (SendStringAndCheckReceive(
socket,
HslProtocol.ProtocolFileDirectoryFiles,
fileManagment.JsonArrayContent).IsSuccess)
{
socket?.Close();
}
}
else if (customer == HslProtocol.ProtocolFileDirectories)
{
List<string> folders = new List<string>();
foreach (var m in GetDirectories(Factory, Group, Identify))
{
DirectoryInfo directory = new DirectoryInfo(m);
folders.Add(directory.Name);
}
Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray());
if (SendStringAndCheckReceive(
socket,
HslProtocol.ProtocolFileDirectoryFiles,
jArray.ToString()).IsSuccess)
{
socket?.Close();
}
}
else
{
// close not supported client
socket?.Close();
}
}
#endregion
#region Object Override
/// <summary>
/// 获取本对象的字符串表示形式
/// </summary>
/// <returns>字符串对象</returns>
public override string ToString()
{
return "UltimateFileServer";
}
#endregion
}
}