-
Notifications
You must be signed in to change notification settings - Fork 1
/
PipeStream.cs
80 lines (66 loc) · 2.2 KB
/
PipeStream.cs
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
namespace TelnetClientServer;
public class PipeStream
{
private readonly string _logPrefix;
private static int _instanceCount;
private readonly Stream _reader;
private readonly Stream _writer;
private readonly byte[] _buffer = new byte[1024];
public PipeStream(Stream reader, Stream writer, string? readerName = null, string? writerName = null)
{
_reader = reader;
_writer = writer;
_logPrefix = $"[ {nameof(PipeStream)}#{++_instanceCount} : {readerName ?? reader.GetType().Name} -> {writerName ?? writer.GetType().Name} ]";
Console.WriteLine($"{_logPrefix} Created.");
}
public void BeginRead()
{
Console.WriteLine($"{_logPrefix} Reading.");
_reader.BeginRead(_buffer, 0, _buffer.Length, BeginReadCallback, null);
}
private void BeginReadCallback(IAsyncResult asyncResult)
{
if (!asyncResult.IsCompleted)
{
Console.WriteLine($"{_logPrefix} Not complete to read.");
return;
}
var bytesRead = 0;
try
{
if (_reader.CanRead)
{
bytesRead = _reader.EndRead(asyncResult);
Console.WriteLine($"{_logPrefix} Bytes read: {bytesRead}");
}
else
{
Console.WriteLine($"{_logPrefix} Can't read.", _logPrefix);
}
}
catch (Exception exception)
{
Console.WriteLine($"{_logPrefix} Error when read: {exception.Message}");
}
if (bytesRead > 0 && _writer.CanWrite)
{
Console.WriteLine($"{_logPrefix} Writing.", _logPrefix);
try
{
_writer.Write(_buffer, 0, bytesRead);
_writer.Flush();
BeginRead();
}
catch (Exception exception)
{
Console.WriteLine($"{_logPrefix} Error when write: {exception.Message}");
}
}
else
{
Console.WriteLine($"{_logPrefix} Closing.", _logPrefix);
_reader.Close();
_writer.Close();
}
}
}