-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathChunkUploadServer.cs
More file actions
77 lines (60 loc) · 1.77 KB
/
ChunkUploadServer.cs
File metadata and controls
77 lines (60 loc) · 1.77 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
using System.Net;
using System.Text;
namespace SimpleHTTPServer;
public class ChunkUploadServer
{
readonly int chunkSize;
readonly int threadCount;
public ChunkUploadServer(int chunkSize, int threadCount)
{
this.chunkSize = chunkSize;
this.threadCount = threadCount;
}
public async Task StartServer(int port)
{
var uri = $"http://localhost:{port}/upload/";
var listener = new HttpListener();
listener.Prefixes.Add(uri);
listener.Start();
Console.WriteLine($"Server started listening at {uri}");
// Wait for a client request
var context = await listener.GetContextAsync();
if (context.Request.HttpMethod == HttpMethod.Post.Method)
{
await ProcessUpload(context);
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
context.Response.Close();
}
}
public async Task ProcessUpload(HttpListenerContext context)
{
var fileName = Path.GetFileName(context.Request.Headers["X-Filename"]);
if (context.Request.ContentLength64 > chunkSize * threadCount)
{
Console.WriteLine("File size exceeds chunk capacity.");
context.Response.Abort();
return;
}
var barrier = new Barrier(threadCount + 1);
for (int i = 0; i < threadCount; i++)
{
int chunkNumber = i + 1;
var threadTask = Task.Run(() =>
{
Console.WriteLine($"Thread {chunkNumber} processed stream chunk.");
barrier.SignalAndWait();
});
}
barrier.SignalAndWait();
var message = $"File '{fileName}' uploaded successfully...";
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(message);
context.Response.StatusCode = (int)HttpStatusCode.Created;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter(s))
await writer.WriteAsync(message);
context.Response.Close();
}
}