add 500ms Timeout to TcpChannel
This commit is contained in:
parent
2a1e7cce93
commit
48fe29ef88
|
@ -106,11 +106,3 @@ public partial class DcDcRecord
|
|||
//
|
||||
// #endregion IDcDc
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -6,9 +6,15 @@ namespace InnovEnergy.Lib.Protocols.Modbus.Channels;
|
|||
|
||||
public class TcpChannel : ConnectionChannel<TcpClient>
|
||||
{
|
||||
private const Int32 TimeoutMs = 500; // TODO: parametrize
|
||||
|
||||
public TcpChannel(Ip4Address ip4Address,Boolean closeAfterSuccessfulRead = false,
|
||||
Boolean closeAfterSuccessfulWrite = false) : this(ip4Address.Host, ip4Address.Port, closeAfterSuccessfulRead, closeAfterSuccessfulWrite)
|
||||
public TcpChannel(Ip4Address ip4Address,
|
||||
Boolean closeAfterSuccessfulRead = false,
|
||||
Boolean closeAfterSuccessfulWrite = false) :
|
||||
this(ip4Address.Host,
|
||||
ip4Address.Port,
|
||||
closeAfterSuccessfulRead,
|
||||
closeAfterSuccessfulWrite)
|
||||
{
|
||||
|
||||
}
|
||||
|
@ -18,7 +24,30 @@ public class TcpChannel : ConnectionChannel<TcpClient>
|
|||
Boolean closeAfterSuccessfulRead = false,
|
||||
Boolean closeAfterSuccessfulWrite = false) : base(closeAfterSuccessfulRead, closeAfterSuccessfulWrite)
|
||||
{
|
||||
TcpClient Open() => new(hostname, port);
|
||||
TcpClient Open()
|
||||
{
|
||||
var tcpClient = new TcpClient
|
||||
{
|
||||
LingerState = new LingerOption(false, 0),
|
||||
NoDelay = true,
|
||||
ReceiveTimeout = TimeoutMs,
|
||||
SendTimeout = TimeoutMs
|
||||
};
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
|
||||
var connected = tcpClient
|
||||
.ConnectAsync(hostname, port, cts.Token)
|
||||
.AsTask()
|
||||
.Wait(TimeoutMs);
|
||||
|
||||
if (connected)
|
||||
return tcpClient;
|
||||
|
||||
cts.Cancel();
|
||||
throw new Exception($"Failed to connect to {hostname}:{port}");
|
||||
}
|
||||
|
||||
_Open = Open;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue