C# Telnet Client 端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace Telnet_Client_Example
{
public partial class Form1 : Form
{
//telnet 參數
NetworkStream telnetStream_A;
TcpClient telnet_A;
Thread t;
bool telnet_receiving = false;
string Telnet_out;
delegate void Display(string s);
string IP = "120.0.0.1";
int PORT = 23;
public Form1()
{
InitializeComponent();
}
private void ShowMessage(string buf)
{
tb_Output.AppendText(buf);
}
private void btn_Connect_Click(object sender, EventArgs e)
{
IP = tb_Ip.Text;
PORT = Convert.ToInt16(tb_Port.Text);
Telnet_Connect(IP, PORT);
}
private void Telnet_Connect(string ip, int port)
{
try
{
tb_Output.Text = "";
telnet_A = new TcpClient();
telnet_A.SendTimeout = 1000;
telnet_A.ReceiveTimeout = 1000;
telnet_A.Connect(IP, PORT);
if (telnet_A.Connected)
{
telnetStream_A = telnet_A.GetStream();
//開啟執行緒做接收
telnet_receiving = true;
t = new Thread(Telnet_Read);
t.Start();
Thread.Sleep(100);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//telnet 讀資料
private void Telnet_Read()
{
try
{
while (telnet_receiving)
{
if (telnetStream_A.DataAvailable)
{
byte[] bytes = new byte[telnet_A.ReceiveBufferSize];
int numBytesRead = telnetStream_A.Read(bytes, 0, (int)telnet_A.ReceiveBufferSize);
Array.Resize(ref bytes, numBytesRead);
Telnet_out = Encoding.ASCII.GetString(bytes);
//委派顯示
Display d = new Display(ShowMessage);
this.Invoke(d, new Object[] { Telnet_out });
}
Thread.Sleep(20);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//telnet 寫資料
public void Telnet_SendData(string s)
{
byte[] bytWrite_telnet_A;
if (s != null)
{
try
{
bytWrite_telnet_A = Encoding.ASCII.GetBytes(s + "\r");
//寫入資料
telnetStream_A.Write(bytWrite_telnet_A, 0, bytWrite_telnet_A.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void tb_Input_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
Telnet_SendData(tb_Input.Text);
tb_Input.Clear();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}