今天仔細研究了一下Learning hard Learning hard的博客《C#網絡編程系列五:TCP編程》,就花了一下午的時間重敲了一下上面的代碼,加深了對運輸層TCP協議的瞭解,詳細的關於TCP的介紹,請你們看上面的博客,裏面有詳細的介紹,俺是個菜鳥,處於學習階段,就不班門弄斧了編程
下面我把我花了一下午重寫的代碼貼到下面,供你們參考,有什麼意見請指出,不勝感激服務器
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Net.Sockets;
- using System.IO;
- using System.Net;
- using System.Threading;
- namespace Tcp客戶端
- {
- public partial class Form1 : Form
- {
- #region 變量定義
- //聲明變量
- private TcpClient tcpClient = null;
- private NetworkStream networkStream = null;
- private BinaryReader reader;
- private BinaryWriter writer;
- //申明委託
- //顯示消息
- private delegate void ShowMessage(string str);
- private ShowMessage showMessageCallback;
- //申明委託
- //顯示狀態
- private delegate void ShowStatus(string str);
- private ShowStatus showStatusCallback;
- //申明委託
- //清空消息
- private delegate void ResetMessage();
- private ResetMessage resetMessageCallback;
- #endregion
- public Form1()
- {
- InitializeComponent();
- //顯示消息
- showMessageCallback = showMessage;
- //顯示狀態
- showStatusCallback = showStatus;
- //清空消息
- resetMessageCallback = resetMessage;
- }
- #region 定義委託函數
- //顯示消息
- private void showMessage(string str)
- {
- lbMessageView.Items.Add(tcpClient.Client.RemoteEndPoint);
- lbMessageView.Items.Add(str);
- lbMessageView.TopIndex = lbMessageView.Items.Count - 1;
- }
- //顯示狀態
- private void showStatus(string str)
- {
- toolStripStatusLabel1.Text = str;
- }
- //清空消息
- private void resetMessage()
- {
- tbMessage.Text = "";
- tbMessage.Focus();
- }
- #endregion
- //創建鏈接
- private void btnConnection_Click(object sender, EventArgs e)
- {
- // 經過一個線程發起請求,多線程
- Thread connectThread = new Thread(ConnectToServer);
- connectThread.Start();
- }
- private void ConnectToServer()
- {
- try
- {
- //調用委託
- statusStrip1.Invoke(showStatusCallback, "正在鏈接……");
- if (txtIP.Text == string.Empty || txtPort.Text == string.Empty)
- {
- MessageBox.Show("請先輸入服務器的IP地址和端口號");
- }
- IPAddress ipaddress = IPAddress.Parse(txtIP.Text);
- tcpClient = new TcpClient();
- tcpClient.Connect(ipaddress, int.Parse(txtPort.Text));
- //延時操做
- Thread.Sleep(1000);
- if (tcpClient != null)
- {
- statusStrip1.Invoke(showStatusCallback, "鏈接成功");
- networkStream = tcpClient.GetStream();
- reader = new BinaryReader(networkStream);
- writer = new BinaryWriter(networkStream);
- }
- }
- catch
- {
- statusStrip1.Invoke(showStatusCallback, "鏈接失敗");
- Thread.Sleep(1000);
- statusStrip1.Invoke(showStatusCallback, "就緒");
- }
- }
- //斷開鏈接
- private void btnDisconnect_Click(object sender, EventArgs e)
- {
- if (reader != null)
- {
- reader.Close();
- }
- if (writer != null)
- {
- writer.Close();
- }
- if (tcpClient != null)
- {
- // 斷開鏈接
- tcpClient.Close();
- }
- toolStripStatusLabel1.Text = "斷開鏈接";
- }
- //接受消息
- private void btnRecev_Click(object sender, EventArgs e)
- {
- Thread receiveThread = new Thread(receiveMessage);
- receiveThread.Start();
- }
- private void receiveMessage()
- {
- statusStrip1.Invoke(showStatusCallback, "接受中");
- try
- {
- string receivemessage = reader.ReadString();
- lbMessageView.Invoke(showMessageCallback, receivemessage);
- }
- catch
- {
- if (reader != null)
- {
- reader.Close();
- }
- if (writer != null)
- {
- writer.Close();
- }
- if (tcpClient != null)
- {
- tcpClient.Close();
- }
- statusStrip1.Invoke(showStatusCallback, "斷開了鏈接");
- }
- }
- //清除消息
- private void btnClear_Click(object sender, EventArgs e)
- {
- lbMessageView.Items.Clear();
- }
- //發送消息
- private void btnSend_Click(object sender, EventArgs e)
- {
- Thread sendThread = new Thread(SendMessage);
- sendThread.Start(tbMessage.Text);
- }
- private void SendMessage(object state)
- {
- try
- {
- statusStrip1.Invoke(showStatusCallback, "正在發送……");
- writer.Write(state.ToString());
- Thread.Sleep(3000);
- writer.Flush();
- statusStrip1.Invoke(showStatusCallback, "完畢");
- tbMessage.Invoke(resetMessageCallback, null);
- lbMessageView.Invoke(showMessageCallback, state.ToString());
- }
- catch
- {
- if (reader != null)
- {
- reader.Close();
- }
- if (writer != null)
- {
- writer.Close();
- }
- if (tcpClient != null)
- {
- tcpClient.Close();
- }
- statusStrip1.Invoke(showStatusCallback, "斷開了鏈接");
- }
- }
- //關閉
- private void btnClose_Click(object sender, EventArgs e)
- {
- this.Close();
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Net.Sockets;
- using System.Net;
- using System.IO;
- using System.Threading;
- namespace Tcp服務器
- {
- public partial class Form1 : Form
- {
- #region 變量
- private const int Port = 51388;
- private TcpListener tcpListener = null;
- private TcpClient tcpClient = null;
- IPAddress ipaddress;
- private NetworkStream networkStream = null;
- private BinaryReader reader;
- private BinaryWriter writer;
- // 申明委託
- // 顯示消息
- private delegate void ShowMessage(string str);
- private ShowMessage showMessageCallback;
- // 申明委託
- // 顯示狀態
- private delegate void ShowStatus(string str);
- private ShowStatus showStatusCallBack;
- // 申明委託
- // 清空消息
- private delegate void ResetMessage();
- private ResetMessage resetMessageCallBack;
- #endregion
- public Form1()
- {
- InitializeComponent();
- #region 實例化委託
- // 顯示消息
- showMessageCallback = showMessage;
- // 顯示狀態
- showStatusCallBack = showStatus;
- // 重置消息
- resetMessageCallBack = resetMessage;
- #endregion
- ipaddress = IPAddress.Loopback;
- txtIP.Text = ipaddress.ToString();
- txtPort.Text = Port.ToString();
- }
- #region 定義回調函數
- // 顯示消息
- private void showMessage(string str)
- {
- lbMessageView.Items.Add(tcpClient.Client.RemoteEndPoint);
- lbMessageView.Items.Add(str);
- lbMessageView.TopIndex = lbMessageView.Items.Count - 1;
- }
- // 顯示狀態
- private void showStatus(string str)
- {
- toolStripStatusLabel1.Text = str;
- }
- // 清空消息
- private void resetMessage()
- {
- tbMessage.Text = string.Empty;
- tbMessage.Focus();
- }
- #endregion
- //開始監聽
- private void btnStart_Click(object sender, EventArgs e)
- {
- tcpListener = new TcpListener(ipaddress, Port);
- tcpListener.Start();
- //啓動一個線程來接受請求
- Thread acceptThread = new Thread(acceptClientConnect);
- acceptThread.Start();
- }
- private void acceptClientConnect()
- {
- statusStrip1.Invoke(showStatusCallBack, "正在監聽……");
- Thread.Sleep(1000);
- try
- {
- statusStrip1.Invoke(showStatusCallBack, "等待鏈接");
- tcpClient = tcpListener.AcceptTcpClient();
- if (tcpListener != null)
- {
- statusStrip1.Invoke(showStatusCallBack, "接受到鏈接");
- networkStream = tcpClient.GetStream();
- reader = new BinaryReader(networkStream);
- writer = new BinaryWriter(networkStream);
- }
- }
- catch
- {
- statusStrip1.Invoke(showStatusCallBack, "中止監聽");
- Thread.Sleep(1000);
- statusStrip1.Invoke(showStatusCallBack, "就緒");
- }
- }
- //關閉監聽
- private void btnStop_Click(object sender, EventArgs e)
- {
- tcpListener.Stop();
- }
- //接受
- private void btnReceiv_Click(object sender, EventArgs e)
- {
- statusStrip1.Invoke(showStatusCallBack, "接受消息中");
- try
- {
- string receivemessage = reader.ReadString();
- lbMessageView.Invoke(showMessageCallback, receivemessage);
- }
- catch
- {
- if (reader != null)
- {
- reader.Close();
- }
- if (writer != null)
- {
- writer.Close();
- }
- if (tcpClient != null)
- {
- tcpClient.Close();
- }
- statusStrip1.Invoke(showStatusCallBack, "斷開了鏈接");
- Thread acceptThread = new Thread(acceptClientConnect);
- acceptThread.Start();
- }
- }
- //清空消息
- private void btnClear_Click(object sender, EventArgs e)
- {
- lbMessageView.Items.Clear();
- }
- //發送
- private void btnSend_Click(object sender, EventArgs e)
- {
- Thread sendThread = new Thread(SendMessage);
- sendThread.Start(tbMessage.Text);
- }
- private void SendMessage(object state)
- {
- statusStrip1.Invoke(showStatusCallBack, "正在發送");
- try
- {
- writer.Write(state.ToString());
- Thread.Sleep(3000);
- writer.Flush();
- statusStrip1.Invoke(showStatusCallBack, "完畢");
- tbMessage.Invoke(resetMessageCallBack, null);
- lbMessageView.Invoke(showMessageCallback, state.ToString());
- }
- catch
- {
- if (reader != null)
- {
- reader.Close();
- }
- if (writer != null)
- {
- writer.Close();
- }
- if (tcpClient != null)
- {
- tcpClient.Close();
- }
- statusStrip1.Invoke(showStatusCallBack, "斷開了鏈接");
- // 從新開啓一個線程等待新的鏈接
- Thread acceptThread = new Thread(acceptClientConnect);
- acceptThread.Start();
- }
- }
- //斷開鏈接
- private void btnDispose_Click(object sender, EventArgs e)
- {
- if (reader != null)
- {
- reader.Close();
- }
- if (writer != null)
- {
- writer.Close();
- }
- if (tcpClient != null)
- {
- // 斷開鏈接
- tcpClient.Close();
- }
- toolStripStatusLabel1.Text = "斷開鏈接";
- // 啓動一個線程等待接受新的請求
- Thread acceptThread = new Thread(acceptClientConnect);
- acceptThread.Start();
- }
- }
- }
進行通訊的時候,首先將TCP服務器端打開監聽,客戶端輸入IP地址和端口號進行鏈接,鏈接成功後就能夠進行通訊了網絡