forked from VerifyTests/DiffEngine
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPiperServer.cs
87 lines (79 loc) · 2.41 KB
/
PiperServer.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
using System.Net;
using System.Net.Sockets;
static class PiperServer
{
public static async Task Start(
Action<MovePayload> move,
Action<DeletePayload> delete,
Cancel cancel = default)
{
TcpListener? listener = default;
try
{
listener = new(IPAddress.Loopback, PiperClient.Port);
listener.Start();
while (true)
{
if (cancel.IsCancellationRequested)
{
break;
}
try
{
await Handle(listener, move, delete, cancel);
}
catch (TaskCanceledException)
{
break;
}
catch (ObjectDisposedException)
{
//when task is cancelled socket is disposed
break;
}
catch (Exception exception)
{
if (cancel.IsCancellationRequested)
{
break;
}
ExceptionHandler.Handle("Failed to receive payload", exception);
}
}
}
finally
{
listener?.Stop();
}
}
static async Task Handle(TcpListener listener, Action<MovePayload> move, Action<DeletePayload> delete, Cancel cancel)
{
await using (cancel.Register(listener.Stop))
{
using var client = await listener.AcceptTcpClientAsync(cancel);
using var reader = new StreamReader(client.GetStream());
var payload = await reader.ReadToEndAsync(cancel);
if (payload.Contains("\"Type\":\"Move\"") ||
payload.Contains("\"Type\": \"Move\""))
{
move(Serializer.Deserialize<MovePayload>(payload));
}
else if (payload.Contains("\"Type\":\"Delete\"") ||
payload.Contains("\"Type\": \"Delete\""))
{
delete(Serializer.Deserialize<DeletePayload>(payload));
}
else
{
if (payload.Length > 0)
{
throw new($"Unknown payload: {payload}");
}
}
if (client.Connected)
{
client.Close();
}
}
}
}