首页 > 其他 > 详细

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

时间:2021-04-23 16:48:57      阅读:34      评论:0      收藏:0      [点我收藏+]

客户端:

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-异步封装客户端与服务端类

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!