using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; namespace WinXPClient { public partial class MainForm : Form { private TcpClient tcpClient; private NetworkStream netStream; private Thread thread; //private string control = "000000"; public MainForm() { InitializeComponent(); } /// <summary> /// 开启连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStart_Click(object sender, EventArgs e) { try { if (this.txtIPAddress.Text == "" || this.txtIPAddress.Text == null || this.txtPort.Text == "" || this.txtPort.Text == null) { MessageBox.Show("请先设置地址和端口号"); } else { this.rtbMsg.AppendText("正在请求连接" + this.txtIPAddress.Text + "/r"); tcpClient = new TcpClient(this.txtIPAddress.Text, Convert.ToInt32(this.txtPort.Text)); } } catch { MessageBox.Show("对方没回应,请输入正确地址和端口"); this.rtbMsg.AppendText("连接失败,请重新连接!"+"/r"); } } private void btnLED_Click(object sender, EventArgs e) { this.rtbMsg.AppendText("正在执行LED命令"+"/r"); try { netStream = tcpClient.GetStream(); if (netStream.CanWrite) { string control = "cmdLED"; byte[] by = System.Text.Encoding.ASCII.GetBytes(control.ToCharArray()); netStream.Write(by, 0, by.Length); netStream.Flush(); thread = new Thread(new ThreadStart(receive)); thread.Start(); //thread.Abort(); } } catch (Exception ee) { this.rtbMsg.AppendText(ee.Message + "/r"); MessageBox.Show(ee.Message); } } /// <summary> /// 测试连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTestConnect_Click(object sender, EventArgs e) { this.rtbMsg.AppendText("正在测试连接…"); try { netStream = tcpClient.GetStream(); if (netStream.CanWrite) { string control = "Tesing"; byte[] by = System.Text.Encoding.ASCII.GetBytes(control.ToCharArray()); netStream.Write(by, 0, by.Length); netStream.Flush(); thread = new Thread(new ThreadStart(receive)); thread.Start(); } } catch (Exception ee) { this.rtbMsg.AppendText(ee.Message + "/r"); MessageBox.Show(ee.Message); } } //receive函数,反馈服务器的连接与被控制状态.反馈控制码为3位. public void receive() { byte[] bb = new byte[3]; int i = netStream.Read(bb, 0, 3); //用字符串变量ss表示控制反馈码 string ss = System.Text.Encoding.ASCII.GetString(bb); //con代表连接成功的服务器反馈码 if (ss == "con") { MessageBox.Show("连接成功"); this.rtbMsg.AppendText("连接" + this.txtIPAddress.Text + " 成功。" + "/r"); } //ctr代表控制成功的服务器反馈码 if (ss == "led") { this.rtbMsg.AppendText("控制LED命令执行完毕" + "/r"); //tcpClient.Close(); } //tcpClient.Close(); } private void MainForm_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; } } }