-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpServer.cs
93 lines (86 loc) · 2.96 KB
/
HttpServer.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System.Net.Sockets;
using System.Net;
namespace SimpleMultithreadedAsuncHttpServer
{
class HttpServer : IDisposable
{
private readonly TcpListener _listener;
private readonly List<HttpServerClient> _clients;
private long _clientID;
public CancellationTokenSource source;
public CancellationToken token;
public HttpServer(int port)
{
_listener = new TcpListener(IPAddress.Any, port);
_clients = new List<HttpServerClient>();
_clientID = 0;
source = new CancellationTokenSource();
token = source.Token;
}
public async Task ListenAsync()
{
try
{
_listener.Start();
Console.WriteLine("Сервер стартовал на " + _listener.LocalEndpoint);
while (true)
{
try
{
TcpClient client = await _listener.AcceptTcpClientAsync(token);
Console.WriteLine("Подключение: " + client.Client.RemoteEndPoint + " > " + client.Client.LocalEndPoint);
lock (_clients)
{
_clients.Add(new HttpServerClient(client, c => { lock (_clients) { _clients.Remove(c); } c.Dispose(); },_clientID));
_clientID++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}
catch (ObjectDisposedException ex)
{
if (ex.ObjectName.EndsWith("Socket"))
Console.WriteLine("Сервер остановлен.");
else
throw ex;
}
source.Dispose();
Console.WriteLine("Сервер остановлен нормально.");
}
public void Stop()
{
_listener.Stop();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
bool disposed;
protected virtual void Dispose(bool disposing)
{
if (disposed)
throw new ObjectDisposedException(typeof(HttpServer).FullName);
disposed = true;
_listener.Stop();
if (disposing)
{
Console.WriteLine("Отключаю подключенных клиентов...");
lock (_clients)
{
foreach (HttpServerClient client in _clients)
{
client.Dispose();
}
}
Console.WriteLine("Клиенты отключены.");
}
}
~HttpServer() => Dispose(false);
}
}