//
// TcpClient.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Data;
using NosSmooth.Comms.Data;
using Remora.Results;
namespace NosSmooth.Comms.Core.Tcp;
///
/// A client using tcp.
///
public class TcpClient : IClient
{
private readonly string _hostname;
private readonly int _port;
private readonly System.Net.Sockets.TcpClient _client;
///
/// Initializes a new instance of the class.
///
/// The hostname to connet to.
/// Teh port to connect to.
public TcpClient(string hostname, int port)
{
_hostname = hostname;
_port = port;
_client = new System.Net.Sockets.TcpClient();
}
///
public ConnectionState State => _client.Connected ? ConnectionState.Open : ConnectionState.Closed;
///
public Stream ReadStream => _client.GetStream();
///
public Stream WriteStream => _client.GetStream();
///
public void Disconnect()
{
_client.Close();
}
///
public async Task ConnectAsync(CancellationToken ct = default)
{
try
{
await _client.ConnectAsync(_hostname, _port, ct);
return Result.FromSuccess();
}
catch (Exception e)
{
return e;
}
}
}