-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathConnection.cs
More file actions
84 lines (69 loc) · 2.5 KB
/
Connection.cs
File metadata and controls
84 lines (69 loc) · 2.5 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using ZusiTcpInterface.Converters;
using ZusiTcpInterface.DOM;
namespace ZusiTcpInterface
{
public class Connection : IDisposable
{
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly TcpClient _tcpClient;
private readonly Task _dataForwardingTask;
private readonly IBlockingCollection<DataChunkBase> _receivedDataChunks = new BlockingCollectionWrapper<DataChunkBase>();
private bool _hasBeenDisposed;
private readonly MessageReceiver _messageReceiver;
internal Connection(string clientName, string clientVersion, IEnumerable<CabInfoAddress> neededData, IPEndPoint endPoint, RootNodeConverter rootNodeConverter)
{
_tcpClient = new TcpClient(AddressFamily.InterNetworkV6);
var socket = _tcpClient.Client;
socket.DualMode = true;
socket.Connect(endPoint);
var cancellableStream = new CancellableBlockingStream(_tcpClient.GetStream(), _cancellationTokenSource.Token);
var binaryReader = new BinaryReader(cancellableStream);
var binaryWriter = new BinaryWriter(cancellableStream);
_messageReceiver = new MessageReceiver(binaryReader, rootNodeConverter);
var handshaker = new Handshaker(_messageReceiver, binaryWriter, ClientType.ControlDesk, clientName, clientVersion,
neededData);
handshaker.ShakeHands();
_dataForwardingTask = Task.Run((Action) DataForwardingLoop);
}
private void DataForwardingLoop()
{
while (true)
{
IProtocolChunk protocolChunk;
try
{
protocolChunk = _messageReceiver.GetNextChunk();
}
catch (OperationCanceledException)
{
// Teardown requested
return;
}
_receivedDataChunks.Add((DataChunkBase) protocolChunk);
}
}
public IBlockingCollection<DataChunkBase> ReceivedDataChunks
{
get { return _receivedDataChunks; }
}
public void Dispose()
{
if (_hasBeenDisposed)
return;
_cancellationTokenSource.Cancel();
if (_dataForwardingTask != null && !_dataForwardingTask.Wait(500))
throw new TimeoutException("Failed to shut down message forwarding task within timeout.");
if (_tcpClient != null)
_tcpClient.Close();
_receivedDataChunks.CompleteAdding();
_hasBeenDisposed = true;
}
}
}