This commit is contained in:
2023-10-06 14:17:20 +09:00
parent a3a0cc201b
commit c699009897
3 changed files with 13 additions and 5 deletions

View File

@@ -9,6 +9,8 @@ namespace ConsoleApp.TelnetSamples
{
internal class AsyncStreamTelnetClient : IAsyncTelnetClient
{
private CancellationTokenSource _cts = new CancellationTokenSource();
public event EventHandler<string> MessageCallback;
public event EventHandler<Exception> ErrorCallback;
@@ -25,7 +27,8 @@ namespace ConsoleApp.TelnetSamples
await _client.ConnectAsync(ip, port);
_stream = _client.GetStream();
Task.Run(ReadAsync);
_cts = new CancellationTokenSource();
Task.Run(ReadAsync, _cts.Token);
}
catch (Exception)
{
@@ -41,6 +44,10 @@ namespace ConsoleApp.TelnetSamples
byte[] readBuffer = new byte[1024];
while (true)
{
Thread.Sleep(50);
if (_cts.IsCancellationRequested)
break;
int bytesRead = await this._stream.ReadAsync(readBuffer);
if (bytesRead < 1)
break;
@@ -95,7 +102,7 @@ namespace ConsoleApp.TelnetSamples
_stream.Close();
}
_cts.Cancel();
_client.Close();
_client.Dispose();