TCP通信 小例子

服务端

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Text;
  7 using System.Windows.Forms;
  8 using System.Net;
  9 using System.Net.Sockets;
 10 using System.Threading;
 11  
 12 namespace CSharp_003服务端
 13 {
 14     public partial class frmMain : Form
 15     {
 16         //定义回调//定义委托
 17         private delegate void ShowReceiveMsgCallBack(string text);
 18         //声明回调//声明委托
 19         private ShowReceiveMsgCallBack showReceiveMsgCallBack;
 20  
 21         private TcpListener server;   //声明Tcp监听对象
 22         private Thread tcpListenerThread;   //声明Tcp监听线程
 23         private Int32 port;     //端口号
 24         private IPAddress localAddr;    //本地IP地址
 25         private Thread receiveDataThread;   //声明接收数据的线程
 26  
 27         public frmMain()
 28         {
 29             InitializeComponent();
 30         }
 31  
 32         private void btnListen_Click(object sender, EventArgs e)
 33         {
 34             string strPort = txtServerPort.Text;
 35             if (strPort == "")
 36             {
 37                 MessageBox.Show("请输入监听端口");
 38                 return;
 39             }
 40            try
 41            {
 42                // 设置监听的端口
 43                port = Int32.Parse(strPort);
 44                localAddr = IPAddress.Parse("127.0.0.1");
 45                if (port > 0)
 46                 {
 47                     //启动服务端监听线程
 48                    tcpListenerThread = new Thread(StartListenerTcp);
 49                    tcpListenerThread.Start();
 50                 }
 51                 else
 52                     MessageBox.Show("监听端口号必须大于0,建议使用大于1024的端口");
 53            }
 54            catch (System.Exception ex)
 55            {
 56                
 57            }
 58     }
 59  
 60         //Tcp监听线程的实现函数
 61         private void StartListenerTcp()
 62         {
 63             server = new TcpListener(localAddr, port);
 64             server.Start(); // 开始监听客户端的申请
 65             MessageBox.Show("服务已启动。。。");
 66             
 67             
 68             try
 69             {
 70                 //启动接收数据的线程
 71                 receiveDataThread = new Thread(ReceiveMsg);
 72                 receiveDataThread.Start();
 73             }
 74             catch (Exception e)
 75             {
 76                 MessageBox.Show(e.ToString());
 77                 receiveDataThread.Abort();
 78             }
 79             
 80         }
 81  
 82         //接收消息线程的实现函数
 83         private void ReceiveMsg()
 84         {
 85             TcpClient client = server.AcceptTcpClient();
 86             NetworkStream netStream = client.GetStream();
 87             while (true)
 88             {
 89                 try
 90                 {
 91                     netStream = client.GetStream();
 92                     //获取数据
 93                     byte[] getData = new byte[1024];
 94                     netStream.Read(getData, 0, getData.Length);
 95                     //转换为字符串形式
 96                     string strMsg = Encoding.Default.GetString(getData);
 97                     //将接收的消息添加到列表中//调用回调
 98                     lstReceiveMsg.Invoke(showReceiveMsgCallBack, strMsg);
 99                     //将数据返回
100                     netStream.Write(getData, 0, getData.Length);
101                 }
102                 catch (ThreadAbortException)
103                 {
104  
105                 }
106                 catch (System.Exception ex)
107                 {
108                     MessageBox.Show(ex.Message);
109                     //释放相关资源
110                     if (netStream != null)
111                     {
112                         netStream.Dispose();
113                     }
114                     break;
115                 }
116             }
117         }
118  
119        
120  
121         //回调函数的实现函数//被委托的函数
122         private void AddMsgToList(string text)
123         {
124             lstReceiveMsg.Items.Add(text);
125         }
126  
127         private void frmMain_Load(object sender, EventArgs e)
128         {
129             //初始化回调//实例化委托
130             showReceiveMsgCallBack = new ShowReceiveMsgCallBack(AddMsgToList);
131         }
132     }
133 }
View Code

客户端

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Text;
  7 using System.Windows.Forms;
  8 //引入命名空间
  9 using System.Net;
 10 using System.Net.Sockets;
 11 using System.Threading;
 12  
 13 namespace CSharp_003_同步TCP客户端
 14 {
 15     public partial class frmMain : Form
 16     {
 17         //定义回调//定义委托
 18         private delegate void ShowReceiveMsgCallBack(string text);
 19         //声明回调//声明委托
 20         private ShowReceiveMsgCallBack showReceiveMsgCallBack;
 21         //定义回调
 22         private delegate void SetProgressBarValueCallBack();
 23         //声明回调
 24         private SetProgressBarValueCallBack setProgressBarValueCallBack;
 25  
 26         private TcpClient myTcpClient;  //声明TCP客户端
 27         private NetworkStream netStream;    //声明网络数据流
 28         private Thread receiveDataThread;   //声明接收数据进程
 29  
 30  
 31         public frmMain()
 32         {
 33             InitializeComponent();
 34         }
 35  
 36         private void frmMain_Load(object sender, EventArgs e)
 37         {
 38             //初始化回调//实例化委托
 39             showReceiveMsgCallBack = new ShowReceiveMsgCallBack(AddMsgToList);
 40             //初始化回调
 41             setProgressBarValueCallBack = new SetProgressBarValueCallBack(SetProgressBarValue);
 42         }
 43  
 44         private void btnConnect_Click(object sender, EventArgs e)
 45          {
 46              //创建并实例化IP终结点
 47              IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(txtServerIp.Text), Convert.ToInt32(txtServerPort.Text));
 48              //实例化TCP客户端
 49              myTcpClient = new TcpClient();
 50              try
 51              {
 52                  //发起TCP连接
 53                  myTcpClient.Connect(iPEndPoint);
 54                  //获取绑定的网络数据流
 55                  netStream = myTcpClient.GetStream();
 56                  //实例化接收数据进程
 57                  receiveDataThread = new Thread(ReceiveMsg);
 58                  receiveDataThread.Start();
 59              }
 60              catch (System.Exception ex)
 61              {
 62                  MessageBox.Show(ex.Message);
 63              }
 64        
 65          }
 66  
 67         //接收消息线程
 68         private void ReceiveMsg()
 69         {
 70             MessageBox.Show("客户端已连接服务器!");
 71  
 72            while (true)
 73            {
 74                 try
 75                 {
 76                     //获取数据
 77                     byte[] getData = new byte[1024];
 78                     netStream.Read(getData,0,getData.Length);
 79                     //转换为字符串形式
 80                     string strMsg = Encoding.Default.GetString(getData);
 81                     //将接收的消息添加到列表中//调用回调
 82                     lstReceiveMsg.Invoke(showReceiveMsgCallBack,strMsg);
 83                     //改变进度条
 84                     pgMsg.Invoke(setProgressBarValueCallBack);
 85                 }
 86                 catch(ThreadAbortException)
 87                 {
 88  
 89                 }
 90                 catch (System.Exception ex)
 91                 {
 92                     MessageBox.Show(ex.Message);
 93                     //释放相关资源
 94                     if(netStream != null)
 95                     {
 96                         netStream.Dispose();
 97                     }
 98                     break;
 99                 }
100            }
101         }
102         
103         //回调函数的实现函数//被委托的函数
104         private void AddMsgToList(string text)
105         {
106             lstReceiveMsg.Items.Add(text);
107         }
108  
109         //回调函数的实现函数
110         private void SetProgressBarValue()
111         {
112             if (pgMsg.Maximum == pgMsg.Value)
113             {
114                 pgMsg.Value = 1;
115             }
116             else
117             {
118                 pgMsg.Value++;
119             }
120         }
121  
122         private void btnSendMsg_Click(object sender, EventArgs e)
123         {
124             byte[] sendData;
125             sendData=Encoding.Default.GetBytes(txtMsg.Text);
126             netStream.Write(sendData,0,sendData.Length);
127         }
128  
129         private void btnDisConnect_Click(object sender, EventArgs e)
130         {
131             //销毁TCP客户端和网络数据流的实例
132             myTcpClient.Close();
133             netStream.Dispose();
134             receiveDataThread.Abort();
135         }
136  
137         
138     }
139 }
View Code
原文地址:https://www.cnblogs.com/anyihen/p/12832658.html