telnet comm

main
syneffort 2 years ago
parent 9e30320f43
commit 4b4d64331e
  1. 10
      PacticeSolution/PacticeSolution.sln
  2. 9
      PacticeSolution/TelnetCommunicator/App.xaml
  3. 17
      PacticeSolution/TelnetCommunicator/App.xaml.cs
  4. 10
      PacticeSolution/TelnetCommunicator/AssemblyInfo.cs
  5. 34
      PacticeSolution/TelnetCommunicator/MainWindow.xaml
  6. 70
      PacticeSolution/TelnetCommunicator/MainWindow.xaml.cs
  7. 172
      PacticeSolution/TelnetCommunicator/Telnet/AsyncSocketTelnetClient.cs
  8. 17
      PacticeSolution/TelnetCommunicator/Telnet/IAsyncTelnetClient.cs
  9. 44
      PacticeSolution/TelnetCommunicator/Telnet/OneTimeTelnetSender.cs
  10. 75
      PacticeSolution/TelnetCommunicator/Telnet/TAP.cs
  11. 10
      PacticeSolution/TelnetCommunicator/TelnetCommunicator.csproj

@ -143,9 +143,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WPFCanvas", "WPFCanvas\WPFC
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Capture", "Capture\Capture.csproj", "{08694854-976A-4551-A4CA-7BA80CFCC33C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FakeGoogle", "FakeGoogle\FakeGoogle.csproj", "{CCEBB074-4E79-42C1-83D6-E531B49B3372}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FakeGoogle", "FakeGoogle\FakeGoogle.csproj", "{CCEBB074-4E79-42C1-83D6-E531B49B3372}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlurText", "BlurText\BlurText.csproj", "{28D8D0D9-7053-4AE3-99A7-C1192511F084}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlurText", "BlurText\BlurText.csproj", "{28D8D0D9-7053-4AE3-99A7-C1192511F084}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelnetCommunicator", "TelnetCommunicator\TelnetCommunicator.csproj", "{06C7726F-CD7F-409A-97ED-343FFCD13BAA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -441,6 +443,10 @@ Global
{28D8D0D9-7053-4AE3-99A7-C1192511F084}.Debug|Any CPU.Build.0 = Debug|Any CPU
{28D8D0D9-7053-4AE3-99A7-C1192511F084}.Release|Any CPU.ActiveCfg = Release|Any CPU
{28D8D0D9-7053-4AE3-99A7-C1192511F084}.Release|Any CPU.Build.0 = Release|Any CPU
{06C7726F-CD7F-409A-97ED-343FFCD13BAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{06C7726F-CD7F-409A-97ED-343FFCD13BAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{06C7726F-CD7F-409A-97ED-343FFCD13BAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{06C7726F-CD7F-409A-97ED-343FFCD13BAA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

@ -0,0 +1,9 @@
<Application x:Class="TelnetCommunicator.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TelnetCommunicator"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace TelnetCommunicator
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

@ -0,0 +1,34 @@
<Window x:Class="TelnetCommunicator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TelnetCommunicator"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Margin="0 0 0 0" Content=" Telnet Communicator"
VerticalContentAlignment="Center"
FontSize="30" FontWeight="Bold" Foreground="White" Background="Black"/>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Vertical">
<Button x:Name="btnStatus" Content="Status" Click="btnStatus_Click"/>
</StackPanel>
<TextBox x:Name="tbMessage" Grid.Column="1"
VerticalScrollBarVisibility="Auto"
Background="Black" Foreground="LimeGreen"/>
</Grid>
</Grid>
</Window>

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using TelnetCommunicator.Telnet;
namespace TelnetCommunicator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private TAP _tap;
public MainWindow()
{
InitializeComponent();
InitInstance();
}
private void InitInstance()
{
_tap = new TAP("200.200.200.123", 23);
_tap.ErrorHandler += On_Received;
}
private async void btnStatus_Click(object sender, RoutedEventArgs e)
{
string response = await _tap.SendMessage("STA");
tbMessage.AppendText(GetInfo(response) + Environment.NewLine);
tbMessage.ScrollToEnd();
}
private void On_Received(object sender, Exception e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
tbMessage.AppendText(e.Message + Environment.NewLine);
tbMessage.ScrollToEnd();
}));
}
private string GetInfo(string message)
{
string[] lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (line.IndexOf("Serial Num:") < 0)
continue;
string tmp = line.ToLower().Replace(" ", "");
return tmp.Substring(tmp.IndexOf(":") + 1);
}
return "";
}
}
}

@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TelnetCommunicator.Telnet
{
public enum TelnetMode
{
Continuously = 0,
Once,
}
public class AsyncSocketTelnetClient
{
public event EventHandler<string> MessageCallback;
private Socket _socket;
private Thread _readThread;
public async Task Connect(string ip, int port = 23, TelnetMode mode = TelnetMode.Continuously)
{
try
{
Close();
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.ReceiveTimeout = 1000;
IPAddress ipAddress = Dns.GetHostAddresses(ip)[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
await _socket.ConnectAsync(ipEndPoint);
switch (mode)
{
case TelnetMode.Continuously:
_readThread = new Thread(ReadAsync);
break;
case TelnetMode.Once:
_readThread = new Thread(ReadAsyncOnce);
break;
}
_readThread.Start();
}
catch (Exception)
{
throw;
}
}
private async void ReadAsync()
{
try
{
StringBuilder sb = new StringBuilder();
byte[] readBuffer = new byte[1024];
while (true)
{
int readByte = _socket == null ? 0 : await _socket.ReceiveAsync(readBuffer, SocketFlags.None);
if (readByte < 1)
break;
string data = Encoding.ASCII.GetString(readBuffer, 0, readByte);
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;
}
}
private async void ReadAsyncOnce()
{
try
{
StringBuilder sb = new StringBuilder();
byte[] readBuffer = new byte[1024];
while (true)
{
int readByte = _socket == null ? 0 : await _socket.ReceiveAsync(readBuffer, SocketFlags.None);
if (readByte < 1)
{
if (sb.Length > 0 && this.MessageCallback != null)
this.MessageCallback(this, sb.ToString());
break;
}
string data = Encoding.ASCII.GetString(readBuffer, 0, readByte);
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();
}
Close();
}
catch (Exception)
{
throw;
}
}
public async Task SendMessage(string message)
{
if (_socket == null)
return;
try
{
message += "\r\n";
byte[] sendBuffer = Encoding.ASCII.GetBytes(message);
await _socket.SendAsync(sendBuffer, SocketFlags.None);
}
catch (Exception)
{
throw;
}
}
public void Close()
{
if (_socket == null)
return;
try
{
_socket.Shutdown(SocketShutdown.Both);
//_readThread.Abort();
_socket.Close();
_socket.Disconnect(true);
_socket.Dispose();
}
catch (Exception)
{
throw;
}
}
}
}

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelnetCommunicator.Telnet
{
public interface IAsyncTelnetClient
{
public event EventHandler<string> MessageCallback;
void Connect(string ip, int port = 23);
void SendMessage(string message);
void Close();
}
}

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TelnetCommunicator.Telnet
{
public class OneTimeTelnetSender
{
private AsyncSocketTelnetClient _client;
private string _ip;
private int _port;
private EventHandler<string> _messageCallback;
public OneTimeTelnetSender(string ip, int port = 23, EventHandler<string> messageCallback = null)
{
_ip = ip;
_port = port;
_client = new AsyncSocketTelnetClient();
_messageCallback = messageCallback;
_client.MessageCallback -= _messageCallback;
_client.MessageCallback += _messageCallback;
}
public async void Send(string message)
{
try
{
await _client.Connect(_ip, _port, TelnetMode.Once);
await _client.SendMessage(message);
}
catch (Exception ex)
{
if (_messageCallback != null)
_messageCallback(this, ex.Message);
}
}
}
}

@ -0,0 +1,75 @@
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();
}
}
}

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
Loading…
Cancel
Save