下面的代码在 Windows 窗体应用程序中运行良好,但我需要在控制台中运行它。
namespace TelnetApp
{
public partial class TelnetForm : Form
{
public TelnetForm()
{
InitializeComponent();
}
private Socket clientSocket;
IPAddress hostAddress;
public void telnetSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Connect)
{
MessageBox.Show("Service Is Running", hostAddress.ToString(),
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Service Is not Running", e.SocketError.ToString(),
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message, "Service Is not Running",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void TelnetButton_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(IPTextBox.Text))
return;
if (string.IsNullOrEmpty(PortTextBox.Text))
return;
int port;
hostAddress = IPAddress.Parse(IPTextBox.Text);
int.TryParse(PortTextBox.Text, out port);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();
telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(hostAddress,port);
telnetSocketAsyncEventArgs.Completed += new
EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);
clientSocket.ConnectAsync(telnetSocketAsyncEventArgs);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message, "Service Is not Running",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}
}
}
}