You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

129 lines
2.9 KiB

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp.TelnetSamples
{
internal class AsyncSocketTelnetClient : IAsyncTelnetClient
{
private CancellationTokenSource _cts;
public event EventHandler<string> MessageCallback;
public event EventHandler<Exception> ErrorCallback;
private Socket _socket;
public async void Connect(string ip, int port = 23)
{
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);
_cts = new CancellationTokenSource();
Task.Run(ReadAsync, _cts.Token);
}
catch (Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
private async void ReadAsync()
{
try
{
StringBuilder sb = new StringBuilder();
byte[] readBuffer = new byte[1024];
while (true)
{
//Thread.Sleep(100);
if (_cts.IsCancellationRequested)
break;
int bytesRead = await _socket.ReceiveAsync(readBuffer);
if (bytesRead < 1)
{
if (sb.Length > 0 && this.MessageCallback != null)
this.MessageCallback(this, sb.ToString());
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 ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
public async void SendCommand(string command)
{
try
{
command = command.Replace(" ", "");
if (string.IsNullOrEmpty(command))
return;
command += "\r\n";
byte[] sendBytes = Encoding.ASCII.GetBytes(command);
await _socket.SendAsync(sendBytes);
}
catch (Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
public void Close()
{
try
{
if (_socket == null)
return;
_cts.Cancel();
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
_socket.Dispose();
}
catch (Exception ex)
{
if (this.ErrorCallback != null)
this.ErrorCallback(this, ex);
}
}
}
}