-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcpServer.cs
85 lines (76 loc) · 2.81 KB
/
TcpServer.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
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using SingleSand.Utils;
namespace SingleSand.TcpServer
{
internal class TcpServer : ITcpServer
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private const int MaxConnectionsInQueue = 100000;
private readonly TcpListener _listener;
private readonly IClientSessionFactory _sessionFactory;
private readonly IClientHandlerFactory _handlerFactory;
private readonly IDictionary<IClientSession, Task> _clients = new Dictionary<IClientSession, Task>();
public TcpServer(IPAddress ip, int port, IClientSessionFactory sessionFactory, IClientHandlerFactory handlerFactory)
{
_sessionFactory = sessionFactory;
_handlerFactory = handlerFactory;
_listener = new TcpListener(ip, port);
}
public ICollection<IClientSession> ActiveClients
{
get { return _clients.Keys; }
}
public async Task ListenIncomingClients(CancellationToken cancellation)
{
_listener.Start(MaxConnectionsInQueue);
try
{
while (!cancellation.IsCancellationRequested)
{
var newClient = await _listener.AcceptTcpClientAsync()
.CancelWith(() => (TcpClient) null, cancellation);
if (newClient == null)
continue;
var handler = await _handlerFactory.Get(newClient);
var newSession = await _sessionFactory.Get(newClient, handler);
newSession.Finish += OnSessionFinish;
var clientTask = ClientCommunicate(cancellation, newSession);
_clients.Add(newSession, clientTask);
}
}
finally
{
_listener.Stop();
}
await Task.WhenAll(_clients.Values);
}
private static async Task ClientCommunicate(CancellationToken cancellation, IClientSession session)
{
using (session)
{
Log.Debug("Starting client session {0}", session);
await session.Communicate(cancellation);
Log.Debug("Finishing client session {0}", session);
}
}
private void OnSessionFinish(IClientSession session)
{
session.Finish -= OnSessionFinish;
_clients.Remove(session);
}
public void Dispose()
{
foreach (var client in _clients)
{
client.Key.Dispose();
}
_clients.Clear();
_listener.Server.Dispose();
}
}
}