-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTcpServer.cs
More file actions
53 lines (45 loc) · 1.32 KB
/
TcpServer.cs
File metadata and controls
53 lines (45 loc) · 1.32 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
using System.Net;
using System.Net.Sockets;
namespace SerializersBenchmark.Network.Abstractions;
public abstract class TcpServer(int port) : IServer
{
private readonly TcpListener _tcpListener = new(IPAddress.Loopback, port);
private TcpClient _connectedClient;
protected bool TeardownStarted;
public void Start()
{
_tcpListener.Start();
//listen asynchronously
Task.Run(async () =>
{
try
{
while (true)
{
_connectedClient = await _tcpListener.AcceptTcpClientAsync();
_connectedClient.Client.NoDelay = true; //disable Nagle's algorithm for low latency
await OnClientConnected(_connectedClient);
}
}
catch when (TeardownStarted)
{
//skip
}
});
}
protected abstract Task OnClientConnected(TcpClient client);
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
TeardownStarted = true;
_tcpListener.Stop();
_connectedClient?.Dispose();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}