ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-04-23 13:35:23  阅读:129  来源: 互联网

标签:异步 Socket System Client new null ar public 服务端


客户端:

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,System,Client,new,null,ar,public,服务端
来源: https://www.cnblogs.com/dangnianxiaoqingxin/p/14693343.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有