Socket-异步封装客户端与服务端类

客户端:

class SocketClient
    {
        private byte[] byteRcvbuf;

        public Socket Client { get; set; }

        public string SocketIP { get; set; }

        public uint SocketPort { get; set; }

        private static object Locker = new object();
        private int length=1024*10;

        public SocketClient(string _SocketIP, uint _SocketPort)
        {
            SocketIP = _SocketIP;
            SocketPort = _SocketPort;
        }
        public bool CreateSocket()
        {
            
                if (Client != null)
                {
                   
                    Client.Close();
                    Client = null;
                }          
                Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            
                IPAddress ipAddress = IPAddress.Parse(SocketIP);
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, (int)SocketPort);
                Client.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
                Thread.Sleep(500);                             
                return false;
        }
        private void OnConnect(IAsyncResult ar)
        {
           
                Client.EndConnect(ar);

                byteRcvbuf = new byte[length];
                //Start listening to the data asynchronously
                Client.BeginReceive(byteRcvbuf,
                                                   0,
                                                   byteRcvbuf.Length,
                                                   SocketFlags.None,
                                                   new AsyncCallback(OnReceive),
                                                   null);  
           
        }
        //byte[] lastMsg;
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                System.Threading.Thread.Sleep(10);
                Client.EndReceive(ar);
                //Str = System.Text.Encoding.UTF8.GetString(byteRcvbuf);
                MessageBox.Show(System.Text.Encoding.UTF8.GetString(byteRcvbuf));


                byteRcvbuf = new byte[length];

                Client.BeginReceive(byteRcvbuf,
                                                    0,
                                                    byteRcvbuf.Length,
                                                    SocketFlags.None,
                                                    new AsyncCallback(OnReceive),
                                                    null);

            }
            catch (Exception ex)
            {
                if (Client != null)
                {                   
                    Client.Close();
                    Client = null;
               
                }
            }
        }
        private void OnSend(IAsyncResult ar)
        {
           
                Client.EndSend(ar);
   
        }

        public void SendMsg(byte[] bData)
        {
            lock (Locker)
            {
                if (Client == null || !Client.Connected)
                {
                    return;
                }

                try
                {
                    Client.BeginSend(bData, 0, bData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                }
                catch (System.Exception ex)
                {
                    if (Client != null)
                    {
                      
                        Client.Close();
                        Client = null;
                       
                    }
                }
            }
        }

    }

服务端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerTest
{
    class SocketServer
    {
        Socket listenServerSocket;
       public Socket socket;
        string _ip;
        int _port;
        int length = 1024 * 10;
        byte[] byteDateLine;
        private static object Locker = new object();
        public SocketServer(string ip, int port)
        {
            listenServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _ip = ip;
            _port = port;
           
        }
        public void CreateSocket()
        {
            listenServerSocket.Bind(new IPEndPoint(IPAddress.Parse(_ip), _port));
            listenServerSocket.Listen(10);
            listenServerSocket.BeginAccept(new AsyncCallback(OnConnectRequest), listenServerSocket);
        }
        public void OnConnectRequest(IAsyncResult ar)
        {
            Socket server1 = (Socket)ar.AsyncState;
            socket = server1.EndAccept(ar);
           
            //等待新的客户端连接
            server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);
            while (true)
            {
                byteDateLine = new byte[length];
                int recv = socket.Receive(byteDateLine);
                string stringdata = Encoding.UTF8.GetString(byteDateLine, 0, recv);
                MessageBox.Show(stringdata);
            }

        }
        private void OnSend(IAsyncResult ar)
        {

            socket.EndSend(ar);

        }

        public void SendMsg(byte[] bData)
        {
            lock (Locker)
            {
                if (socket == null || !socket.Connected)
                {
                    return;
                }

                try
                {
                    socket.BeginSend(bData, 0, bData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                }
                catch (System.Exception ex)
                {
                    if (socket != null)
                    {

                        socket.Close();
                        socket = null;

                    }
                }
            }
        }

    }

}

 

posted @ 2021-04-23 13:14  当年小清新  阅读(131)  评论(0编辑  收藏  举报