|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace TelnetCommunicator.Telnet
|
|
|
|
|
{
|
|
|
|
|
public class TAP
|
|
|
|
|
{
|
|
|
|
|
string _ip;
|
|
|
|
|
int _port;
|
|
|
|
|
|
|
|
|
|
public EventHandler<Exception> ErrorHandler;
|
|
|
|
|
|
|
|
|
|
public TAP(string ip, int port)
|
|
|
|
|
{
|
|
|
|
|
_ip = ip;
|
|
|
|
|
_port = port;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<string> SendMessage(string message)
|
|
|
|
|
{
|
|
|
|
|
using (TcpClient client = new TcpClient())
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
string response = "";
|
|
|
|
|
await client.ConnectAsync(_ip, _port);
|
|
|
|
|
using (NetworkStream stream = client.GetStream())
|
|
|
|
|
{
|
|
|
|
|
// First Message
|
|
|
|
|
response += await ReceiveMessage(stream);
|
|
|
|
|
|
|
|
|
|
byte[] sendData = Encoding.ASCII.GetBytes(message + "\r\n");
|
|
|
|
|
await stream.WriteAsync(sendData, 0, sendData.Length);
|
|
|
|
|
|
|
|
|
|
response += await ReceiveMessage(stream);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return response;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
if (this.ErrorHandler != null)
|
|
|
|
|
this.ErrorHandler(this, ex);
|
|
|
|
|
|
|
|
|
|
return "ERROR";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<string> ReceiveMessage(NetworkStream stream)
|
|
|
|
|
{
|
|
|
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
|
byte[] receiveData = new byte[1024];
|
|
|
|
|
|
|
|
|
|
while (true)
|
|
|
|
|
{
|
|
|
|
|
int bytesRead = await stream.ReadAsync(receiveData, 0, receiveData.Length);
|
|
|
|
|
if (bytesRead < 1)
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
|
|
string response = Encoding.ASCII.GetString(receiveData, 0, bytesRead);
|
|
|
|
|
sb.Append(response);
|
|
|
|
|
|
|
|
|
|
if (response.EndsWith("\r\n>"))
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return sb.ToString();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|