telnet samples
This commit is contained in:
105
MySolution/ConsoleApp/TelnetSamples/StreamTelnetClient.cs
Normal file
105
MySolution/ConsoleApp/TelnetSamples/StreamTelnetClient.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using ConsoleApp.TelnetSamples;
|
||||
|
||||
namespace Samples.Telnet
|
||||
{
|
||||
public class StreamTelnetClient : ITelnetClient
|
||||
{
|
||||
private TcpClient _client;
|
||||
private NetworkStream _stream;
|
||||
private StreamReader _reader;
|
||||
private StreamWriter _writer;
|
||||
|
||||
public string Connect(string ip, int port = 23)
|
||||
{
|
||||
try
|
||||
{
|
||||
Close();
|
||||
|
||||
_client = new TcpClient(ip, port);
|
||||
|
||||
// 스트림 생성
|
||||
_stream = _client.GetStream();
|
||||
_reader = new StreamReader(_stream);
|
||||
_writer = new StreamWriter(_stream);
|
||||
_writer.AutoFlush = true;
|
||||
|
||||
return Read();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public string Read()
|
||||
{
|
||||
try
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
byte[] readBuffer = new byte[1024];
|
||||
while (true)
|
||||
{
|
||||
int bytesRead = _reader.BaseStream.Read(readBuffer, 0, readBuffer.Length);
|
||||
if (bytesRead < 1)
|
||||
break;
|
||||
|
||||
string data = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
|
||||
sb.Append(data);
|
||||
|
||||
if (data.EndsWith("\r\n>"))
|
||||
break;
|
||||
}
|
||||
|
||||
// 에코 삭제
|
||||
string read = sb.ToString();
|
||||
int rnIdx = read.IndexOf("\r\n");
|
||||
|
||||
return read.Substring(rnIdx + 1);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public string SendCommand(string command)
|
||||
{
|
||||
try
|
||||
{
|
||||
_writer.WriteLine(command);
|
||||
|
||||
return Read();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_client == null)
|
||||
return;
|
||||
|
||||
if (_stream != null)
|
||||
{
|
||||
_stream.Flush();
|
||||
_stream.Close();
|
||||
}
|
||||
|
||||
_client.Close();
|
||||
_client.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user