telnet samples
This commit is contained in:
95
MySolution/ConsoleApp/TelnetSamples/SocketTelnetClient.cs
Normal file
95
MySolution/ConsoleApp/TelnetSamples/SocketTelnetClient.cs
Normal file
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ConsoleApp.TelnetSamples
|
||||
{
|
||||
public class SocketTelnetClient : ITelnetClient
|
||||
{
|
||||
private Socket _socket;
|
||||
|
||||
public string Connect(string ip, int port = 23)
|
||||
{
|
||||
try
|
||||
{
|
||||
Close();
|
||||
|
||||
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
_socket.ReceiveTimeout = 1000;
|
||||
|
||||
IPAddress ipAddress = IPAddress.Parse(ip);
|
||||
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
|
||||
_socket.Connect(ipEndPoint);
|
||||
|
||||
return Read();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public string Read()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
byte[] readBuffer = new byte[1024];
|
||||
while (true)
|
||||
{
|
||||
int bytesRead = _socket.Receive(readBuffer);
|
||||
if (bytesRead < 1)
|
||||
break;
|
||||
|
||||
string data = Encoding.ASCII.GetString(readBuffer, 0, bytesRead);
|
||||
sb.Append(data);
|
||||
|
||||
if (data.EndsWith("\r\n>"))
|
||||
break;
|
||||
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
|
||||
// 에코 삭제
|
||||
string read = sb.ToString();
|
||||
int rnIdx = read.IndexOf("\r\n");
|
||||
|
||||
return read.Substring(rnIdx + 1);
|
||||
}
|
||||
|
||||
public string SendCommand(string command)
|
||||
{
|
||||
try
|
||||
{
|
||||
command += "\r\n";
|
||||
byte[] sendBytes = Encoding.ASCII.GetBytes(command);
|
||||
_socket.Send(sendBytes);
|
||||
|
||||
return Read();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_socket == null)
|
||||
return;
|
||||
|
||||
_socket.Shutdown(SocketShutdown.Both);
|
||||
_socket.Close();
|
||||
_socket.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user