-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.cs
235 lines (194 loc) · 5.2 KB
/
Client.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
using System.Net.Sockets;
using System.Net;
using System;
using System.Threading.Tasks;
using System.Threading;
namespace SoS;
public abstract class Client : IDisposable
{
internal enum Method { Connect, KeepAlive, Data, Disconnect }
/// <summary>
/// Delay in milleseconds between connection requests
/// </summary>
public int ConnectPollDelay = 1000;
/// <summary>
/// Delay in milleseconds between keep-alive packets
/// </summary>
public int KeepAliveDelay = 1000;
public bool Connected { get; private set; } = false;
private readonly CancellationTokenSource CloseTokenSource = new();
private readonly Socket Socket;
private readonly EndPoint ServerEndPoint;
public Client(Socket socket, EndPoint serverEndPoint)
{
Socket = socket;
ServerEndPoint = serverEndPoint;
#if NET7_0
ReceiveBuffer = GC.AllocateArray<byte>(length: socket.ReceiveBufferSize, pinned: true).AsMemory();
#else
ReceiveBuffer = new(new byte[socket.ReceiveBufferSize]);
#endif
try
{
Task.Run(Receive, CloseTokenSource.Token);
Task.Run(Connect, CloseTokenSource.Token);
Task.Run(KeepAlive, CloseTokenSource.Token);
}
catch (TaskCanceledException) { }
}
/// <summary>
/// Sends the specified <paramref name="data"/> to the server
/// </summary>
/// <param name="data"></param>
/// <exception cref="ObjectDisposedException"></exception>
/// <exception cref="NullReferenceException"></exception>
public void Send(ReadOnlySpan<byte> data)
{
if (Disposed)
throw new ObjectDisposedException(GetType().FullName);
Send(Method.Data, data);
}
/// <summary>
/// Sends a disconnect notice and closes the connection
/// </summary>
/// <exception cref="ObjectDisposedException"></exception>
public void Disconnect()
{
if (Disposed)
throw new ObjectDisposedException(GetType().FullName);
CloseTokenSource.Cancel();
Send(Method.Disconnect);
Connected = false;
}
/// <summary>
/// Closes the connection
/// </summary>
/// <exception cref="ObjectDisposedException"></exception>
public void Close()
{
if (Disposed)
throw new ObjectDisposedException(GetType().FullName);
CloseTokenSource.Cancel();
Connected = false;
OnClose();
}
private bool Disposed = false;
public void Dispose()
{
if (Disposed)
return;
CloseTokenSource.Dispose();
Disposed = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Called when a connection is successfully established with the server
/// </summary>
protected abstract void OnConnect();
/// <summary>
/// Called when data is received from the server
/// </summary>
/// <param name="data"></param>
protected abstract void OnReceive(ReadOnlySpan<byte> data);
/// <summary>
/// Called when a server disconnect notice is received
/// </summary>
protected abstract void OnDisconnect();
/// <summary>
/// Called when the connection is closed
/// </summary>
protected abstract void OnClose();
private async void Connect()
{
try
{
while (!CloseTokenSource.IsCancellationRequested)
{
if (!Connected)
Send(Method.Connect);
await Task.Delay(ConnectPollDelay, CloseTokenSource.Token);
}
}
catch (OperationCanceledException) { }
}
private async void KeepAlive()
{
try
{
while (!CloseTokenSource.IsCancellationRequested)
{
if (Connected)
Send(Method.KeepAlive);
await Task.Delay(KeepAliveDelay, CloseTokenSource.Token);
}
}
catch (OperationCanceledException) { }
}
#if NET7_0
private readonly Memory<byte> ReceiveBuffer;
#else
private readonly ArraySegment<byte> ReceiveBuffer;
#endif
private async void Receive()
{
try
{
while (!CloseTokenSource.IsCancellationRequested)
{
#if NET7_0
SocketReceiveFromResult receiveResult = await Socket.ReceiveFromAsync(ReceiveBuffer, SocketFlags.None, ServerEndPoint, CloseTokenSource.Token);
#else
SocketReceiveFromResult receiveResult = await Socket.ReceiveFromAsync(ReceiveBuffer, SocketFlags.None, ServerEndPoint);
#endif
#if NET7_0
Memory<byte> data = ReceiveBuffer[..receiveResult.ReceivedBytes];
#else
Memory<byte> data = new Memory<byte>(ReceiveBuffer.Array).Slice(0, receiveResult.ReceivedBytes);
#endif
if (data.Length <= 0)
return;
ReadOnlyMemory<byte> methodData = data.Slice(1);
lock (CloseTokenSource)
{
if (CloseTokenSource.IsCancellationRequested)
return;
switch ((Server.Method)data.Span[0])
{
case Server.Method.Data:
OnReceive(methodData.Span);
break;
case Server.Method.AcceptConnect:
OnConnect();
Connected = true;
break;
case Server.Method.Reconnect:
Connected = false;
break;
case Server.Method.Disconnect:
OnDisconnect();
Close();
break;
}
}
}
}
catch (OperationCanceledException) { }
}
private void SendRaw(ReadOnlySpan<byte> data)
{
#if NET7_0
Socket.SendTo(data, SocketFlags.None, ServerEndPoint);
#else
Socket.SendTo(data.ToArray(), SocketFlags.None, ServerEndPoint);
#endif
}
private void Send(Method method) =>
SendRaw(new byte[] { (byte)method });
private void Send(Method method, ReadOnlySpan<byte> data)
{
Span<byte> methodData = new byte[data.Length + 1];
methodData[0] = (byte)method;
data.CopyTo(methodData.Slice(1));
SendRaw(methodData);
}
}