-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsyncTcpLink.cs
More file actions
432 lines (374 loc) · 12.9 KB
/
AsyncTcpLink.cs
File metadata and controls
432 lines (374 loc) · 12.9 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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Extensions.Logging;
using ThreeByte.LinkLib.Shared.Logging;
namespace ThreeByte.LinkLib.TcpLink
{
public class AsyncTcpLink : IDisposable
{
private const int BufferSize = 8092;
private const int MaxDataSize = 100;
private readonly ILogger _logger;
private readonly TcpLinkSettings _settings;
private readonly object _clientLock = new object();
private IAsyncResult? _connectResult;
private readonly List<byte[]> _incomingData = new List<byte[]>();
private bool _isDisposed;
private NetworkStream? _networkStream;
private IAsyncResult? _readResult;
private TcpClient? _tcpClient;
private IAsyncResult? _writeResult;
public AsyncTcpLink(string address, int port)
: this(address, port, true)
{
}
public AsyncTcpLink(string address, int port, bool enabled = true)
{
_settings = new TcpLinkSettings(address, port);
IsEnabled = enabled;
_logger = LogFactory.Create<AsyncTcpLink>();
if (enabled)
{
SafeConnect();
}
}
public bool IsConnected { get; private set; }
public bool IsEnabled { get; private set; } = true;
public string Address => _settings.Address;
public int Port => _settings.Port;
public bool HasData => _incomingData.Count > 0;
/// <summary>
/// Cancels the thread and releases resources.
/// Clients of this class are responsible for calling it.
/// </summary>
public void Dispose()
{
if (_isDisposed)
{
return;
}
_isDisposed = true;
_logger.LogInformation("Cleaning up network resources.");
SafeClose();
}
public event EventHandler<bool>? IsConnectedChanged;
public event EventHandler<bool>? IsEnabledChanged;
public event EventHandler<Exception>? ErrorOccurred;
public event EventHandler? DataReceived;
/// <summary>
/// Sets a value indicating whether messages should be propagated to the network or not
/// </summary>
/// <param name="value"></param>
public void SetEnabled(bool value)
{
IsEnabled = value;
if (!IsEnabled)
{
SafeClose();
}
else if (!IsConnected)
{
SafeConnect();
}
IsEnabledChanged?.Invoke(this, value);
}
/// <summary>
/// Asynchronously sends the TCP message, waiting until the connection is reestablihsed if necessary
/// </summary>
/// <param name="message">binary message to be sent</param>
public void SendMessage(byte[] message)
{
if (!IsEnabled)
{
return;
}
lock (_clientLock)
{
if (_networkStream != null)
{
try
{
_writeResult = _networkStream.BeginWrite(message, 0, message.Length, WriteCallback, null);
}
catch (Exception ex)
{
HandleError(ex, "Cannot Write");
ChangeIsConnected(false);
SafeClose();
SafeConnect();
}
}
else
{
ChangeIsConnected(false);
SafeConnect();
}
}
}
/// <summary>
/// Very carefully checks and shuts down the tcpClient and sets it to null
/// </summary>
private void SafeClose()
{
_logger.LogDebug("Safe Close.");
lock (_clientLock)
{
//Resolve outstanding connections
if (_connectResult != null)
{
//End the connection process
_connectResult = null;
}
if (_readResult != null)
{
//End the read process
_readResult = null;
}
if (_writeResult != null)
{
//End the write process
_writeResult = null;
}
_networkStream = null;
_tcpClient?.Client?.Close();
_tcpClient?.Close();
_tcpClient = null;
lock (_incomingData)
{
_incomingData.Clear();
}
}
ChangeIsConnected(false);
}
private void SafeConnect(object? state)
{
SafeConnect();
}
/// <summary>
/// Carefully check to see if the link is connected or can be reestablished
/// </summary>
private void SafeConnect()
{
_logger.LogDebug("Safe Connect.");
if (_isDisposed)
{
return;
}
lock (_clientLock)
{
if (_connectResult != null)
{
return;
}
if (_tcpClient == null || !_tcpClient.Connected)
{
SafeClose();
_tcpClient = new TcpClient();
}
if (!_tcpClient.Connected)
{
_logger.LogInformation("Connecting: {addr}/{prt}.", _settings.Address, _settings.Port);
try
{
_connectResult = _tcpClient.BeginConnect(_settings.Address, _settings.Port, ConnectCallback, null);
}
catch (Exception ex)
{
HandleError(ex, "Connection Error");
ChangeIsConnected(false);
}
}
}
}
private void ConnectCallback(IAsyncResult asyncResult)
{
_logger.LogInformation("Connect Callback: {addr}/{prt}.", _settings.Address, _settings.Port);
lock (_clientLock)
{
try
{
_networkStream = null;
if (_tcpClient != null)
{
_tcpClient.EndConnect(asyncResult);
_networkStream = _tcpClient.GetStream();
ChangeIsConnected(_tcpClient.Connected);
}
else
{
ChangeIsConnected(false);
}
if (!IsEnabled)
{
SafeClose();
}
}
catch (Exception ex)
{
HandleError(ex, "Connection Error.");
ChangeIsConnected(false);
}
if (_connectResult == asyncResult)
{
_logger.LogDebug("Clearing Connect Result.");
_connectResult = null;
if (IsEnabled)
{
if (!IsConnected)
{
Timer timer = new Timer(
SafeConnect,
DateTime.Now,
TimeSpan.FromSeconds(3),
TimeSpan.FromMilliseconds(-1));
}
else
{
ReceiveData();
}
}
}
}
}
private void WriteCallback(IAsyncResult asyncResult)
{
lock (_clientLock)
{
try
{
_networkStream?.EndWrite(asyncResult);
ChangeIsConnected(true);
}
catch (Exception ex)
{
HandleError(ex, "Error writing to stream.");
SafeConnect();
}
if (_writeResult == asyncResult)
{
_logger.LogDebug("Clearing Write Result.");
_writeResult = null;
}
}
}
private void ReceiveData()
{
if (!IsEnabled)
{
return;
}
byte[] buf = new byte[BufferSize];
lock (_clientLock)
{
if (_networkStream != null)
{
try
{
_readResult = _networkStream.BeginRead(buf, 0, buf.Length, ReadCallback, buf);
ChangeIsConnected(true);
}
catch (Exception ex)
{
HandleError(ex, "Error reading from stream.");
ChangeIsConnected(false);
SafeConnect();
}
}
}
}
private void ReadCallback(IAsyncResult asyncResult)
{
byte[] buffer = (byte[]?)asyncResult.AsyncState ?? Array.Empty<byte>();
bool hasNewData = false;
int bytesRead = 0;
lock (_clientLock)
{
try
{
if (_networkStream != null)
{
bytesRead = _networkStream.EndRead(asyncResult);
}
// If the remote host shuts down the Socket connection and all available data has been received,
// the EndRead method completes immediately and returns zero bytes.
if (bytesRead == 0)
{
SafeClose();
SafeConnect();
}
if (bytesRead > 0)
{
lock (_incomingData)
{
byte[] truncatedBuffer = new byte[bytesRead];
Array.Copy(buffer, truncatedBuffer, bytesRead);
_incomingData.Add(truncatedBuffer);
hasNewData = true;
if (_incomingData.Count > MaxDataSize)
{
// Purge messages from the end of the list to prevent overflow
_logger.LogError("Too many incoming messages to handle: {cnt}.", _incomingData.Count);
_incomingData.RemoveAt(_incomingData.Count - 1);
}
}
ChangeIsConnected(true);
}
}
catch (Exception ex)
{
HandleError(ex, "Error Reading from stream.");
//Try to reopen the connection
SafeConnect();
}
if (_readResult == asyncResult)
{
_logger.LogDebug("Clearing Read Result.");
_readResult = null;
}
}
if (hasNewData && DataReceived != null && !_isDisposed)
{
DataReceived(this, new EventArgs());
}
ReceiveData();
}
/// <summary>
/// Fetches and removes (pops) the next available group of bytes as received on this link in order (FIFO)
/// </summary>
/// <returns>null if the link is not Enabled or there is no data currently queued to return, an array of bytes otherwise.</returns>
public byte[]? GetMessage()
{
if (_isDisposed)
{
throw new ObjectDisposedException("Cannot get message from disposed NetworkLink");
}
//Return null if the link is not enabled
if (!IsEnabled)
{
return null;
}
byte[]? newMessage = null;
lock (_incomingData)
{
if (HasData)
{
newMessage = _incomingData[0];
_incomingData.RemoveAt(0);
}
}
return newMessage;
}
private void ChangeIsConnected(bool value)
{
IsConnected = value;
IsConnectedChanged?.Invoke(this, value);
}
private void HandleError(Exception ex, string message)
{
_logger.LogError(ex, message);
ErrorOccurred?.Invoke(this, ex);
}
}
}