码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2021-04-24 11:54:07      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:result   receive   inter   set   last   class   using   name   lock   

客户端:

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;

                    }
                }
            }
        }

    }

}

 

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

标签:result   receive   inter   set   last   class   using   name   lock   

原文地址:https://www.cnblogs.com/dangnianxiaoqingxin/p/14693343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!