SoFunction
Updated on 2025-04-08

.net socket client instance code sharing


using System;

using ;

using ;

using ;

using ;

using ;

using ;

using ;

 

namespace

{

    public class CacheSocket

    {

        public Socket skClient;

        public string ip = ;

        public int port = -1;

        public int netID;

        // public int timeSleep = 1;

 

//Temporary information sent every time

private byte[] sendData;//Send information

private byte[] receiveData = new byte[1024];//Receive information

        private int receiveN;

        private bool isErr = false;

        //--------

 

        public CacheSocket(int pNetID)

        {

            = pNetID;

            GetConfig();

            Connection();

            Cmd("netid:" + );

        }

 

        public CacheSocket(int pNetID, string pIP, int pPort)

        {

            = pIP;

            = pPort;

            Connection();

            Cmd("netid:" + pNetID);

        }

 

        public string Cmd(string key)

        {

lock (this)//A message is sent and then received is completed in one go

            {

                = Encoding.(key);

 

                try

                {

                    ();

                }

                catch (Exception ex)

                {

                    isErr = true;

                    ("Send" + ).WriteLine();

                    ReSocket(() => { (); });

                }

 

                try

                {

                    = ();

                }

                catch (Exception ex)

                {

                    isErr = true;

                    ReSocket(() => { = (); });

                    ("Receive" + ).WriteLine();

                }

 

                return Encoding.(, 0, );

            }

        }

 

        public delegate void ReSocket_D();

        private void ReSocket(ReSocket_D d)

        {

            if (isErr)

            {

                Connection();

 

                = Encoding.("netid:" + );

                ();

 

                = ();

                if (Encoding.(, 0, ) != "1")

                {

 

                }

 

                d();

                = false;

            }

        }

 

#region Get IP and port

        private void GetConfig()

        {

            = "127.0.0.1";   

            = 1234;

        }

        #endregion

 

#region Connection socket

        private void Connection()

        {

            = new Socket(, , );

IPEndPoint ie = new IPEndPoint((), );//The IP and port of the server

            (ie);

 

            byte[] data = new byte[7];

            = (data);

 

            string s = Encoding.(data, 0, );

            if (s != "success")

            {

throw new Exception("Connection not successful" + s);

            }

        }

        #endregion

    }

}