public partial class TcpForm : Form { private TcpListener listerner; private Thread thread; // public TcpForm() { InitializeComponent(); } private delegate void textCallback(RichTextBox rt, string myStr); private void setText(RichTextBox rt, string text) { if (this.rtRecTxt.InvokeRequired) { textCallback d = new textCallback(setText); this.Invoke(d, new object[] { rt, text }); } else { addLine(rt,text); } } private void receive() { listerner = new TcpListener(IPAddress.Parse(this.tbLocalIP.Text), Int32.Parse(this.tbLocalPort.Text)); listerner.Start(); setText(rtRecTxt, "監聽中..."); while(true){ TcpClient theClient = listerner.AcceptTcpClient(); NetworkStream theStream = theClient.GetStream(); byte[] messageByte = new Byte[64]; theStream.Read(messageByte, 0, messageByte.Length); string readMessage = System.Text.Encoding.BigEndianUnicode.GetString(messageByte); this.rtRecTxt.AppendText(readMessage); } } private void btnStart_Click(object sender, EventArgs e) { try { IPAddress.Parse(this.tbLocalIP.Text); Int32.Parse(this.tbLocalPort.Text); } catch (Exception err) { MessageBox.Show(err.ToString()); return; } if ((thread != null) && (thread.ThreadState == ThreadState.Running)) { MessageBox.Show("已在監聽中..."); return; } try { thread = new Thread(new ThreadStart(receive)); thread.Start(); addLine(rtRecTxt, "啟動中"); } catch (Exception err) { MessageBox.Show(err.ToString()); } } private void btnSend_Click(object sender, EventArgs e) { try { IPAddress.Parse(this.tbRemoteIP.Text); Int32.Parse(this.tbRemotePort.Text); } catch (Exception err) { MessageBox.Show(err.ToString()); return; } if ((thread == null) || (thread.ThreadState != ThreadState.Running)) { MessageBox.Show("請先啟動監聽."); return; } TcpClient theClient = new TcpClient(this.tbRemoteIP.Text, Int32.Parse(this.tbRemotePort.Text)); string send = this.rtSendTxt.Text + "\r\n";//不可以用 Environment.NewLine byte[] messageByte = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray()); NetworkStream theStream = theClient.GetStream(); theStream.Write(messageByte, 0, messageByte.Length); theStream.Close(); theClient.Close(); } private void btnStop_Click(object sender, EventArgs e) { if ((thread == null) || (thread.ThreadState != ThreadState.Running)) { //MessageBox.Show("未啟動監聽."); return; } if ((thread != null) && (thread.ThreadState == ThreadState.Running)) thread.Abort(); if (listerner != null) listerner.Stop(); addLine(rtRecTxt,"停止監聽"); } private void addLine(RichTextBox tb, string data, bool newLine = true) { tb.AppendText(data + Environment.NewLine); } private void TcpForm_FormClosing(object sender, FormClosingEventArgs e) { btnStop_Click(btnStop, null); } }
TCP通訊
週一, 2012-04-16 11:09
#1
TCP通訊