3using System.Net.Sockets;
5using System.Threading.Tasks;
6using Microsoft.Extensions.Logging;
21 private readonly ILogger _logger;
22 private TcpClient _tcpClient;
23 private NetworkStream _stream;
31 public TcpOsdpConnection(
32 TcpClient tcpClient,
int baudRate, ILoggerFactory loggerFactory) : base(baudRate)
35 _tcpClient = tcpClient;
36 _stream = tcpClient.GetStream();
37 _logger = loggerFactory?.CreateLogger<TcpOsdpConnection>();
41 public override async Task<int> ReadAsync(
byte[] buffer, CancellationToken token)
45 var bytes = await _stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(
false);
46 if (bytes == 0) {
IsOpen =
false; }
49 catch (Exception exception)
51 if (exception is not OperationCanceledException &&
IsOpen)
53 if (exception is IOException && exception.InnerException is SocketException)
55 _logger?.LogInformation(
"Error reading TCP stream: {ExceptionMessage}", exception.Message);
59 _logger?.LogWarning(exception,
"Error reading TCP stream");
69 public override async Task WriteAsync(
byte[] buffer)
73 await _stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(
false);
79 _logger?.LogWarning(ex,
"Error writing TCP stream");
89 public override Task
Open() =>
throw new NotSupportedException(
"Connection is already established");
92 public override Task
Close()
96 _tcpClient?.Dispose();
99 return Task.CompletedTask;
Base OSDP connection class.
Task Open()
Open the connection for communications.
Task Close()
Close the connection for communications.
bool IsOpen
Is the connection open and ready to communicate.