-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProgram.cs
79 lines (78 loc) · 1.9 KB
/
Program.cs
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
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace TimeManager
{
class Program
{
static void Main(string[] args)
{
var allowedRate = TimeSpan.FromSeconds(1.5);
var httpListener = new HttpListener();
httpListener.Prefixes.Add("http://+:666/");
var nextAllowedTimestamp = DateTime.UtcNow.Add(allowedRate);
long requestsCount = 0;
var locker = new object();
httpListener.Start();
while (true)
{
try
{
var context = httpListener.GetContext();
Task.Run(() =>
{
try
{
try
{
if (context.Request.Url.AbsoluteUri.EndsWith("/ask"))
{
using (var w = new StreamWriter(context.Response.OutputStream))
{
var timeToSleep = TimeSpan.Zero;
lock(locker)
{
var now = DateTime.UtcNow;
if (now < nextAllowedTimestamp)
{
timeToSleep = nextAllowedTimestamp - now;
nextAllowedTimestamp = nextAllowedTimestamp.Add(allowedRate);
if (nextAllowedTimestamp > now + TimeSpan.FromSeconds(30))
nextAllowedTimestamp = now + TimeSpan.FromSeconds(30);
}
else
nextAllowedTimestamp = now.Add(allowedRate);
}
if (timeToSleep != TimeSpan.Zero)
{
w.WriteLine($"You was freezed for {timeToSleep}");
Console.WriteLine($"Sleeping {timeToSleep}");
Thread.Sleep(timeToSleep);
}
Interlocked.Increment(ref requestsCount);
Console.WriteLine("Go. Requests: " + requestsCount);
w.WriteLine("Go");
}
}
}
finally
{
context.Response.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
});
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
}