~ruther/NosSmooth.Comms

ref: 190a8692e2acbadd240b755dac9b48c7f77d96c1 NosSmooth.Comms/src/Core/NosSmooth.Comms.Core/Tcp/TcpClient.cs -rw-r--r-- 1.6 KiB
190a8692 — Rutherther docs: add missing documentation 2 years ago
                                                                                
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
//
//  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;

/// <summary>
/// A client using tcp.
/// </summary>
public class TcpClient : IClient
{
    private readonly string _hostname;
    private readonly int _port;
    private readonly System.Net.Sockets.TcpClient _client;

    /// <summary>
    /// Initializes a new instance of the <see cref="TcpClient"/> class.
    /// </summary>
    /// <param name="hostname">The hostname to connet to.</param>
    /// <param name="port">Teh port to connect to.</param>
    public TcpClient(string hostname, int port)
    {
        _hostname = hostname;
        _port = port;
        _client = new System.Net.Sockets.TcpClient();
    }

    /// <inheritdoc />
    public ConnectionState State => _client.Connected ? ConnectionState.Open : ConnectionState.Closed;

    /// <inheritdoc />
    public Stream ReadStream => _client.GetStream();

    /// <inheritdoc />
    public Stream WriteStream => _client.GetStream();

    /// <inheritdoc />
    public void Disconnect()
    {
        _client.Close();
    }

    /// <inheritdoc />
    public async Task<Result> ConnectAsync(CancellationToken ct = default)
    {
        try
        {
            await _client.ConnectAsync(_hostname, _port, ct);
            return Result.FromSuccess();
        }
        catch (Exception e)
        {
            return e;
        }
    }
}
Do not follow this link