This commit is contained in:
2023-10-05 17:56:04 +09:00
parent bce6521e43
commit a3a0cc201b
7 changed files with 279 additions and 244 deletions

View File

@@ -12,17 +12,18 @@ namespace ConsoleApp.TelnetSamples
{
internal class AsyncSocketTelnetClient : IAsyncTelnetClient
{
private readonly CancellationTokenSource CTS = new CancellationTokenSource();
private CancellationTokenSource _cts;
public event EventHandler<string> MessageCallback;
public event EventHandler<Exception> ErrorCallback;
private Socket _socket;
private Socket _socket;
public async void Connect(string ip, int port = 23)
{
try
{
Close();
//Close();
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.ReceiveTimeout = 1000;
@@ -31,28 +32,37 @@ namespace ConsoleApp.TelnetSamples
IPEndPoint iPEndPoint = new IPEndPoint(ipAddress, port);
await _socket.ConnectAsync(iPEndPoint);
Task.Run(ReadAsync);
_cts = new CancellationTokenSource();
Task.Run(ReadAsync, _cts.Token);
}
catch (Exception)
catch (Exception ex)
{
throw;
}
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
private async void ReadAsync()
{
try
{
StringBuilder sb = new StringBuilder();
byte[] readBuffer = new byte[1024];
while (true)
{
int bytesRead = await _socket.ReceiveAsync(readBuffer);
if (bytesRead < 1)
if (_cts != null && _cts.IsCancellationRequested)
break;
string data = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
int bytesRead = _cts != null && _cts.IsCancellationRequested ? 0 : await _socket.ReceiveAsync(readBuffer);
if (bytesRead < 1)
{
if (sb.Length > 0 && this.MessageCallback != null)
this.MessageCallback(this, sb.ToString());
break;
}
string data = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
sb.Append(data);
if (!data.EndsWith("\r\n>"))
@@ -69,25 +79,31 @@ namespace ConsoleApp.TelnetSamples
sb.Clear();
}
}
catch (Exception)
{
throw;
}
}
catch (Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
public async void SendCommand(string command)
{
try
{
command = command.Replace(" ", "");
if (string.IsNullOrEmpty(command))
return;
command += "\r\n";
byte[] sendBytes = Encoding.ASCII.GetBytes(command);
await _socket.SendAsync(sendBytes);
}
catch (Exception)
{
throw;
}
}
catch (Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
public void Close()
{
@@ -96,14 +112,17 @@ namespace ConsoleApp.TelnetSamples
if (_socket == null)
return;
_cts.Cancel();
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
_socket.Dispose();
}
catch (Exception)
{
throw;
}
}
catch (Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
}
}