【代码】C#下TCP传输模板

Posted on Posted in 计算机1,398 views

注:该代码创建于2013.12月,是C#下UDP学习时写的代码实例,主要是UdpClient的学习使用。

/*2013-12-08_xia-evan
 * 也可以用UDP的方式自己定义线程实现,本例中用的是封装好的函数 
 * private bool active = false;
 * private Thread thdTcp = null;    //创建一个线程
 * public delegate void DataArrivalEventHandler(string str); //定义了一个托管方法  
 */
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace TCP
{
    public partial class TCPFM : Form
    {
        public TCPFM()
        {
            InitializeComponent();
        }
        /*
         *TcpListener的属性 
         * Active        获取一个值,该值指示 TcpListener 是否正主动侦听客户端连接。
         * ExclusiveAddressUse    
         *   获取或设置一个 Boolean 值,该值指定 TcpListener 是否只允许一个基础套接字来侦听特定端口。
         * LocalEndpoint 获取当前 TcpListener 的基础 EndPoint。
         * Server        获取基础网络 Socket。  
         *      
         *TcpListener的方法 
         * AcceptSocket      接受挂起的连接请求。
         * AcceptSocketAsync 接受挂起的连接请求以作为异步操作。
         * AcceptTcpClient   接受挂起的连接请求。
         * AcceptTcpClientAsync  以异步操作方式接受挂起的连接请求。
         * AllowNatTraversal 启用或禁用针对 TcpListener 实例的网络地址转换 (NAT) 遍历。
         * BeginAcceptSocket  开始一个异步操作来接受一个传入的连接尝试。
         * BeginAcceptTcpClient  开始一个异步操作来接受一个传入的连接尝试。
         * Create                创建一个新的侦听指定端口的 TcpListener 实例。
         * EndAcceptSocket    异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。
         * EndAcceptTcpClient 异步接受传入的连接尝试,并创建新的 TcpClient 来处理远程主机通信。
         * Equals(Object)     确定指定的对象是否等于当前对象。 (继承自 Object。)
         * Finalize     允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
         * GetHashCode  作为默认哈希函数。 (继承自 Object。)
         * GetType      获取当前实例的 Type。 (继承自 Object。)
         * MemberwiseClone    创建当前 Object 的浅表副本。 (继承自 Object。)
         * Pending            确定是否有挂起的连接请求。
         * Start()            开始侦听传入的连接请求。
         * Start(Int32)       启动对具有最大挂起连接数的传入连接请求的侦听。
         * Stop               关闭侦听器。 
         */
         
        //定义了一个托管方法  
        public delegate void DataArrivalEventHandler(string str); 
                           
        #region 异步接收数据
        
        //定义网络端点
        private IPEndPoint ServerEndPoint = null;
        
        //创建网络服务,也就是TCP的Sockets
        private TcpListener tcp_listener = null;//new TcpListener();
                          
        private TcpClient tcp_client = null;
        
        //监听
        public void Listener(int port)
        {
            //将IP地址和端口号以网络端点存储,IPAddress.Any监听所有IP
            ServerEndPoint = new IPEndPoint(IPAddress.Any, port); 
            //如果已经存在则先关闭                
            if (tcp_listener != null)                                        
                tcp_listener.Stop();
            try
            {
                tcp_listener = new TcpListener(ServerEndPoint); 
                tcp_listener.Start(); 
                //【异步】接受客户端的连接请求  ClientConnect为连接的回调函数  
                tcp_listener.BeginAcceptTcpClient(ServerConnectCallBack,tcp_listener);  
            }
            catch (Exception ex)
            {
                if (tcp_listener != null)
                    tcp_listener.Stop(); 
                MessageBox.Show("函数Listener出错:\n" + ex.Message.ToString());
            } 
        }
        
        //接收连接回调函数<接收连接后调用方>
        private void ServerConnectCallBack(IAsyncResult ar)
        {
            try
            { 
                TcpListener listener = (TcpListener)ar.AsyncState;
                TcpClient client = listener.EndAcceptTcpClient(ar); 
                //---------------------------------------------------  
                DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                object[] objs = new object[1];
                objs[0] = "服务器:接收连接:成功!";
                Invoke(showDate, objs); 
                //---------------------------------------------------   
                //while (client.Connected)
                //{
                    //Thread.Sleep(1000);
                    RecieveData(client); 
                //}
            }
            catch(Exception ex)
            {
                MessageBox.Show("函数ServerConnectCallBack出错:\n" + ex.Message.ToString());
            }
        }
        
        //接受数据函数 
        private void RecieveData(TcpClient client)
        {
            // 调用异步方法 BeginReceive 来告知 socket 如何接收数据 
            try
            {
                //创建于服务器连接的数据流
                NetworkStream stream = client.GetStream();
                byte[] data = new byte[1024] ;//Encoding.ASCII.GetBytes(str);
                //【异步】接收数据后
                stream.BeginRead(data, 0, data.Length, RecieveDataCallback, stream);
                string str = Encoding.ASCII.GetString(data);
                //---------------------------------- 
                DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                object[] objs = new object[1];
                objs[0] = String.Format("接收数据为:" + str);
                Invoke(showDate, objs);
                //---------------------------------- 
            }
            catch (Exception ex)
            { 
                MessageBox.Show("函数ServerRecieveData出错:\n" + ex.Message.ToString());
            } 
        } 
        
        //接收数据回调函数 
        private void RecieveDataCallback(IAsyncResult iar)
        {
            //接收到的数据长度. 
            try
            {
                //停一段时间,用于接收
                Thread.Sleep(200);
                NetworkStream stream = (NetworkStream)iar.AsyncState;
                int l = stream.EndRead(iar);
                if (l > 0)
                {  
                    //---------------------------------- 
                    DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                    object[] objs = new object[1];
                    objs[0] = String.Format("接收数据成功!"); 
                    Invoke(showDate, objs); 
                    //---------------------------------- 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数ServerRecieveDataCallback出错:\n" + ex.Message.ToString());
            } 
        }
        
        //发送数据
        public void SendData(TcpClient client, string str)
        {
            try
            {
                if (client.Connected)
                {
                    //创建于服务器连接的数据流
                    NetworkStream stream = client.GetStream();
                    byte[] data = Encoding.ASCII.GetBytes(str);
                    //异步发送数据
                    stream.BeginWrite(data, 0, data.Length, new AsyncCallback(SendDataCallBack), stream);   
                    //----------------------------------
                    DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                    object[] objs = new object[1];
                    objs[0] = "发送数据为:" + str;
                    Invoke(showDate, objs);
                    //----------------------------------
                }
                else
                    throw new Exception("连接未打开!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数SendData出错:\n" + ex.Message.ToString());
            }
        }
        
        //发送数据回调函数<发送结束后调用>
        private void SendDataCallBack(IAsyncResult iar)
        {
            try
            {
                //等待数据发出
                Thread.Sleep(200);
                NetworkStream stream = (NetworkStream)iar.AsyncState;
                int l = stream.EndRead(iar);
                if (l > 0)
                {
                    //----------------------------------
                    DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                    object[] objs = new object[1];
                    objs[0] = "发送数据成功!";
                    Invoke(showDate, objs);
                    //----------------------------------
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数SendDataCallBack出错:\n" + ex.Message.ToString());
            }
        }  
        
        //客户端连接
        public void ClientConnect(string ip, int port)
        {
            try
            {
                tcp_client = new TcpClient();
                //根据服务器的IP地址和端口号 异步连接服务器 
                tcp_client.BeginConnect(ip, Convert.ToInt32(port), new AsyncCallback(ClientConnectCallback), tcp_client);
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数ClientConnect出错:\n" + ex.Message.ToString());
            } 
        } 
        
        //异步连接的回调函数<连接成功后调用>
        private void ClientConnectCallback(IAsyncResult ar)
        { 
            TcpClient t = (TcpClient)ar.AsyncState;
            try
            {
                if (t.Connected)
                { 
                    t.EndConnect(ar);//函数运行到这里就说明连接成功 
                    //----------------------------------
                    DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                    object[] objs = new object[1];
                    objs[0] = "客户端:发起连接:成功!";
                    Invoke(showDate, objs); 
                    //---------------------------------- 
                    SendData(t, txb_message.Text.Trim()); 
                }
                else
                {
                    DataArrivalEventHandler showDate = new DataArrivalEventHandler(MessageAdd);
                    object[] objs = new object[1];
                    objs[0] = "客户端:连接:失败!";
                    Invoke(showDate, objs); 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数ClientConnectCallback出错:\n" + ex.Message.ToString());
            } 
        }
               
        #endregion
        
         
        #region===
        //将接收到的消息放入List
        public void MessageAdd(string str)
        {
            lsb_message.Items.Add(DateTime.Now.ToString() + "\t" + str);
        }
        
        /*//中断连接
        private void btn_int_Click(object sender, EventArgs e)
        {
            try
            {
                if(tcp_client!=null && tcp_client.Connected)
                {
                    tcp_client.Close();
                    MessageAdd("客户端:结束连接!");
                }
                btn_Conn.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数btn_int_Click出错:\n" + ex.Message.ToString());
            }
        }
        
        //建立连接
        private void btn_Conn_Click(object sender, EventArgs e)
        {
            try
            {
                ClientConnect(txb_ip.Text.Trim(), Convert.ToInt32(txb_port.Text.Trim()));
                btn_Conn.Enabled = false; 
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数btn_Conn_Click出错:\n" + ex.Message.ToString());
            }
        }*/
        
        //发送
        private void btn_FS_Click(object sender, EventArgs e)
        {
            try
            {
                ClientConnect(txb_ip.Text.Trim(), Convert.ToInt32(txb_port.Text.Trim())); 
                if (tcp_client != null && tcp_client.Connected)
                {
                    tcp_client.Close();
                    MessageAdd("客户端结束连接!");
                } 
            }
            catch (Exception ex)
            {
                MessageBox.Show("函数btn_FS_Click出错:\n" + ex.Message.ToString());
            }
        } 
        
        //关闭监听
        private void CloseTCPListener()
        {
            if (tcp_listener != null)
                tcp_listener.Stop();
        }
         
        //开始监听
        private void btn_KS_Click(object sender, EventArgs e)
        {
            btn_KS.Enabled = false;
            btn_JS.Enabled = true;
            Listener(2000);
        }
        
        //结束监听
        private void btn_JS_Click(object sender, EventArgs e)
        {
            btn_KS.Enabled = true;
            btn_JS.Enabled = false;
            CloseTCPListener();
        }
         
        //退出程序
        private void TCPFM_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseTCPListener();
            if (tcp_listener != null)
                tcp_listener.Stop();
            if (tcp_client != null)
                tcp_client.Close();
            System.Environment.Exit(0);//Application.Exit(); 
        }
        #endregion
      
    }
}


转载标明出处:https://blog.evanxia.com/2015/12/234