using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace ConsoleApp.TelnetSamples { internal class AsyncStreamTelnetClient : IAsyncTelnetClient { private CancellationTokenSource _cts = new CancellationTokenSource(); public event EventHandler MessageCallback; public event EventHandler ErrorCallback; private TcpClient _client; private NetworkStream _stream; public async void Connect(string ip, int port = 23) { try { Close(); _client = new TcpClient(); await _client.ConnectAsync(ip, port); _stream = _client.GetStream(); _cts = new CancellationTokenSource(); Task.Run(ReadAsync, _cts.Token); } catch (Exception) { throw; } } private async void ReadAsync() { try { StringBuilder sb = new StringBuilder(); 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; string data = Encoding.ASCII.GetString(readBuffer, 0, bytesRead); sb.Append(data); if (!data.EndsWith("\r\n>")) continue; // 에코 삭제 string read = sb.ToString(); int rnIdx = read.IndexOf("\r\n"); read = read.Substring(rnIdx + 1); if (this.MessageCallback != null) this.MessageCallback(this, read); sb.Clear(); } } catch (Exception) { throw; } } public async void SendCommand(string command) { try { command += "\r\n"; byte[] sendBytes = Encoding.ASCII.GetBytes(command); await _stream.WriteAsync(sendBytes); } catch (Exception) { throw; } } public void Close() { try { if (_client == null) return; if (_stream != null) { _stream.Flush(); _stream.Close(); } _cts.Cancel(); _client.Close(); _client.Dispose(); } catch (Exception) { throw; } } } }