Socket网络通信客户端

本文详细介绍了使用C#进行UDP与TCP异步Socket编程的方法。包括如何初始化Socket,建立连接,发送与接收数据,以及关闭连接等关键步骤。通过具体的代码示例,展示了异步Socket编程的实现细节。
摘要由CSDN通过智能技术生成

1、UDP

public class AsyncSocketUdp
    {
        private  Socket socket;
        private IPEndPoint localEP;
        private IPEndPoint remoteEP;
        private byte[] buffer = new byte[1024];//用于存放接收消息

        public event Action<byte[]> OnDataReceive;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="localIP"></param>
        /// <param name="localPort"></param>
        public void Init(IPAddress localIP, int localPort)
        {
            //创建一个Socket实例
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //关联本地终结点
            localEP = new IPEndPoint(localIP, localPort);
            socket.Bind(localEP);
        }

        /// <summary>
        /// 初始化
        /// </summary> 
        public void Init(IPAddress localIP, int localPort, IPAddress remoteIp, int remotePort)
        {
            //创建一个Socket实例
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //关联本地终结点
            localEP = new IPEndPoint(localIP, localPort);
            remoteEP = new IPEndPoint(remoteIp, remotePort);
            socket.Bind(localEP);
        }

        /// <summary>
        /// 接收消息
        /// </summary> 
        public void ReceiveData()
        {
            EndPoint ep = (EndPoint)remoteEP;
            this.socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ep, new AsyncCallback(ReceiveCallBack), null);
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="remoteIp"></param>
        /// <param name="remotePort"></param>
        public void ReceiveData(IPAddress remoteIp,int remotePort)
        {
            remoteEP = new IPEndPoint(remoteIp, remotePort);
            EndPoint ep=(EndPoint)remoteEP;
            this.socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ep, new AsyncCallback(ReceiveCallBack), null); 
        }
        /// <summary>
        /// 接收消息的回调
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallBack(IAsyncResult ar)
        { 
            int length= socket.EndReceive(ar);//结束挂起的异步读取

            byte[] data = new byte[length];
            Array.Copy(buffer, 0, data, 0, data.Length);
            OnDataReceive(data);//接收的数据

            EndPoint ep = (EndPoint)remoteEP;
            this.socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref ep, new AsyncCallback(ReceiveCallBack), null);
        }

        /// <summary>
        /// 异步发送消息
        /// </summary>
        /// <param name="data"></param>
        public void SendData(byte[] data,IPEndPoint remoteEP)
        {
            if (socket != null)
            {
                socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, remoteEP, new AsyncCallback(SendCallBack), null);
            }
        }
        /// <summary>
        /// 发送数据的回调
        /// </summary>
        /// <param name="ar"></param>
        private void SendCallBack(IAsyncResult ar)
        { 
            int length = socket.EndSend(ar);//结束挂起的异步发送
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            if (socket != null)
            {
                socket.Close();
            }
        }

    }
View Code

2、TCP

public class AsyncSocketTcp
    {
        private Socket socket;
        private IPEndPoint localEP;
        private IPEndPoint remoteEP;
        private byte[] buffer = new byte[1024];//用于存放接收消息

        public event Action<byte[]> OnDataReceive;

        /// <summary>
        /// tcp连接
        /// </summary>
        /// <param name="remoteIP"></param>
        /// <param name="remotePort"></param>
        public void Connet(IPAddress remoteIP,int remotePort)
        {
            //创建一个Socket实例
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            //建立连接
            remoteEP=new IPEndPoint(remoteIP, remotePort);
            socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallBack), this.socket); 
        }

        /// <summary>
        /// tcp连接
        /// </summary> 
        public void Connet(IPAddress localIP, int localPort,IPAddress remoteIP, int remotePort)
        {
            //创建一个Socket实例
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //建立连接
            localEP = new IPEndPoint(localIP, localPort);
            remoteEP = new IPEndPoint(remoteIP, remotePort);
            socket.Bind(localEP);//绑定本地终结点
            socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallBack), this.socket);
        }

        /// <summary>
        /// 连接请求的回调
        /// </summary>
        /// <param name="ar"></param>
        private void ConnectCallBack(IAsyncResult ar)
        {
            Socket socketHandle =(Socket)ar.AsyncState;
            if (socketHandle.Connected)
            {
                socketHandle.EndConnect(ar);//结束挂起的异步连接请求
                socketHandle.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
            }
            else
            {
                MessageBox.Show("连接失败");
            } 
        }
        /// <summary>
        /// 接收数据的回调
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallBack(IAsyncResult ar)
        {
           int length=socket.EndReceive(ar);//结束挂起的异步读取
           if (length > 0)
           {
               byte[] data = new byte[length];
               Array.Copy(buffer, 0, data, 0, length);
               OnDataReceive(data);

               socket.BeginReceive(buffer, 0, buffer.Length,SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
           }
           else
           {

           }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="data"></param>
        public void SendData(byte[] data)
        {
            if (socket != null)
            {
                socket.Send(data);
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            if (socket != null)
            {
                socket.Close();
            }
        }

    }
View Code

 

转载于:https://www.cnblogs.com/LY-HeroesRebor/p/9934000.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值