public OpcClient(string destination, int destinationPort = OPC_DEFAULT_PORT)
{
var destinationAddress = IPAddress.Parse(destination);
this.cancelSource = new CancellationTokenSource();
var task = Task.Factory.StartNew(() =>
{
while (!this.cancelSource.IsCancellationRequested)
{
readyToSend.WaitOne();
readyToSend.Reset();
byte[] data;
lock (this.lockObject)
{
data = this.sendData.ToArray();
}
try
{
lock (this.socketLock)
{
// Create socket if we need one
if (this.socket == null)
{
this.socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
this.socket.NoDelay = true;
this.socket.Connect(destinationAddress, destinationPort);
}
}
if (data.Length > 0)
this.socket.Send(data);
}
catch (Exception ex)
{
log.Warn(ex, "Failed to send OPC data");
if (this.socket != null && this.socket.Connected)
this.socket.Close();
this.socket = null;
}
}
if (this.socket != null)
{
try
{
this.socket.Close();
this.socket.Dispose();
}
catch (Exception ex)
{
log.Warn(ex, "Failed to close socket");
}
this.socket = null;
}
}, cancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Executor.Current.Register(this);
}