[System.Net] Help me to dected if client is disconnected

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • NewLegend
    New Member
    • Feb 2010
    • 2

    [System.Net] Help me to dected if client is disconnected

    Hello i'm writing a class for network all works fine but when client disconnected my code can't dected it so if u can help me or say is there an error on the code i will be glad ,alot of thanks

    Code:
    public class NetCore
        {
            private int             MAX_CONNECTIONS = Settings.Default.MAX_CONNECTIONS;
            // ----
    
            public int              m_Port;
            public int              m_ActiveClients;
            public int              i;
            public TcpClient[]         m_Coneections;
    
            // ----
            private TcpListener     m_Listner;
            private ProcessVar      m_ListenVar;
            private ProcessVar      m_PacketVar;
    
            // ----
            public NetCore(int iPort)
            {
                m_Port = iPort;
                // ----
                m_Coneections = new TcpClient[MAX_CONNECTIONS];
                m_ActiveClients = 0;
                // ----
                m_ListenVar.m_Thread = new Thread(ProcessListen);
                m_PacketVar.m_Thread = new Thread(ProcessPacket);
                // ----
                m_ListenVar.m_Idle = 1000;
                m_PacketVar.m_Idle = 1;
            }
            //--------------------------------------------------------------------------------
            // # Name   : ProcessListen
            // # Desc   : Listen to new Clients accsept them and call OnConnect
            // # Status : Finished
            //--------------------------------------------------------------------------------
    
            private void ProcessListen()
            {
                while (m_ListenVar.m_Factor)
                {
                    if (m_Listner.Pending())
                    {
                       TcpClient Client = m_Listner.AcceptTcpClient();
                       OnConnect(Client);
                        
                    }
                    // ----
                    Thread.Sleep(m_ListenVar.m_Idle);
                }
            }
    
            //--------------------------------------------------------------------------------
            // # Name   : ProcessPacket
            // # Desc   : get the packets and check if connection still alive
            // # Status : not found yet if client is connected or not
            //--------------------------------------------------------------------------------
    
            private void ProcessPacket()
            {
                byte[] Recv;
                // --------
                while (m_PacketVar.m_Factor)
                {
                    if (m_ActiveClients > 0)
                    {
                        for (i = 0; i != m_ActiveClients; i++)
                        {
                            try
                            {
                                if (m_Coneections[i].Available > 0)
                                {
                                    Recv = new byte[m_Coneections[i].Available];
                                    int ret = m_Coneections[i].Client.Receive(Recv, Recv.Length, );
                                    // ---
                                    if (ret > 0)
                                    {
                                        OnRecv(m_Coneections[i], Recv);
                                    }
                                    else
                                    {
                                        OnDisconnect(m_Coneections[i]);
                                    }
                                }
                                else if (!m_Coneections[i].Connected)
                                {
                                    // ---
                                    OnDisconnect(m_Coneections[i]);
                                    continue;
                                }
                            }
                            catch (Exception x)
                            {
                                
                                OnDisconnect(m_Coneections[i]);
                            }
                        }
                    }
                    // ----
                    Thread.Sleep(m_PacketVar.m_Idle);
                }
            }
    
            //--------------------------------------------------------------------------------
    
            public bool Create()
            {
                bool bResult = true;
                try
                {
                    // ----
                    m_Listner = new TcpListener(IPAddress.Any, m_Port);
                    m_Listner.Start();
                    // -----
                    m_ListenVar.m_Factor = true;
                    m_ListenVar.m_Thread.Start();
                    // -----
                    m_PacketVar.m_Factor = true;
                    m_PacketVar.m_Thread.Start();
                    // ----
                    OnCreate();
                    // -----
                    bResult = true;
                }
                catch (Exception x)
                {
                    OnCreate(x);
                    // -----
                    bResult = false;
                }
                // -----
                return bResult;
            }
            //--------------------------------------------------------------------------------
    
            public void Close()
            {
                OnClose();
            }
    
            //--------------------------------------------------------------------------------
    
            public virtual void OnConnect(TcpClient uClient)
            {
                m_Coneections[m_ActiveClients] = uClient;
                m_ActiveClients++;
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnDisconnect(TcpClient uClient)
            {
                m_ActiveClients--;
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnRecv(TcpClient uClient, byte[] bRecvBytes)
            {
    
            }
            public virtual void OnClose()
            {
                for (i = 0; i != m_ActiveClients; i++)
                {
                    m_Coneections[i].Close();
                }
                // -----
                m_ListenVar.m_Factor = false;
                m_ListenVar.m_Thread.Abort();
                // -----
                m_PacketVar.m_Factor = false;
                m_PacketVar.m_Thread.Abort();
                // -----
                m_ActiveClients = 0;
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnCreate()
            {
    
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnCreate(Exception x)
            {
    
            }
    
            //--------------------------------------------------------------------------------
    
            private struct ProcessVar
            {
                public Thread  m_Thread;
                public bool m_Factor;
                public int m_Idle;
    
            }
        }
    i made one more code for Async but same problem i dont know how to get if client is disconnected so i can delete him from Object struct






    Code:
        //--------------------------------------------------------------------------------
    
        public class StateObject
        {
            public Socket workSocket        = null;
            public const int BufferSize     = 1024;
            public byte[] buffer            = new byte[BufferSize];
            public StringBuilder sb         = new StringBuilder();
        }
    
        //--------------------------------------------------------------------------------
        public class NetCore
        {
            // ------
            public int                  m_Port;
            public int                  m_maxQueue;
            // ------
            private Socket              m_Listner;
            private IPEndPoint          m_LocalEPoint;
            private ProcessVar          m_ListenVar;
            private ManualResetEvent    m_allDone;
            // ------
            private int                 m_iTemp;
    
            //--------------------------------------------------------------------------------
    
            public NetCore(int iPort)
            {
    
                // ----
                m_Port = iPort;
                // ----
                m_LocalEPoint = new IPEndPoint(IPAddress.Any, m_Port);
                m_Listner = new Socket(m_LocalEPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                m_allDone = new ManualResetEvent(false);
                // ----
                m_ListenVar.m_Thread = new Thread(ProcessListen);
                //m_PacketVar.m_Thread = new Thread(ProcessPacket);
                // ----
                m_ListenVar.m_Idle = 1000;
                //m_PacketVar.m_Idle = 1;
            }
            //--------------------------------------------------------------------------------
            // # Name   : Create
            // # Desc   : Create the Listen Process , etc..
            // # Status : --
            //--------------------------------------------------------------------------------
    
            public bool Create()
            {
                bool bReturn = false;
                // ------
                try
                {
                    // ------
                    m_Listner.Bind(m_LocalEPoint);
                    m_Listner.Listen(m_maxQueue);
                    // ------
                    m_ListenVar.m_Factor = true;
                    m_ListenVar.m_Thread.Start();
                    // ------
                    OnCreate();
                    // ------
                    bReturn = true;
                }
                catch (SocketException x)
                {
                    OnCreate(x);
                    bReturn = false;
                }
    
                // ------
                return bReturn;
            }
            //--------------------------------------------------------------------------------
            // # Name   : Close
            // # Desc   : --
            // # Status : --
            //--------------------------------------------------------------------------------
    
            public void Close()
            {
            }
            //--------------------------------------------------------------------------------
            // # Name   : ProcessListen
            // # Desc   : Listen to new Clients accsept them and call OnConnect
            // # Status : Finished
            //--------------------------------------------------------------------------------
    
            private void ProcessListen()
            {
                while (m_ListenVar.m_Factor)
                {
                    m_allDone.Reset();
    
                    m_Listner.BeginAccept(new AsyncCallback(ProcessAccept), m_Listner);
    
                    m_allDone.WaitOne();
                }
            }
            //--------------------------------------------------------------------------------
    
            private void ProcessAccept(IAsyncResult SyncResult)
            {
                m_allDone.Set();
    
                Socket Listener = (Socket)SyncResult.AsyncState;
                Socket Handler = Listener.EndAccept(SyncResult);
    
                OnConnect(Handler);
    
                StateObject StateObj = new StateObject();
                StateObj.workSocket = Handler;
    
                Handler.BeginReceive(StateObj.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ProcessRecv), StateObj);
            }
            //--------------------------------------------------------------------------------
    
            private void ProcessRecv(IAsyncResult SyncResult)
            {
                StateObject StateObj = (StateObject)SyncResult.AsyncState;
                Socket Handler = StateObj.workSocket;
    
                m_iTemp = Handler.EndReceive(SyncResult);
    
                if (m_iTemp > 0)
                {
                    OnRecv(StateObj.buffer, Handler);
                }
    
    
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnCreate()
            {
    
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnCreate(SocketException x)
            {
    
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnConnect(Socket Client)
            {
    
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnDisconnect(Socket Client)
            {
    
            }
            //--------------------------------------------------------------------------------
    
            public virtual void OnRecv(byte[] buffer, Socket Client)
            {
    
            }
            //--------------------------------------------------------------------------------
    
            private struct ProcessVar
            {
                public Thread m_Thread;
                public bool m_Factor;
                public int m_Idle;
    
            }
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Smarter in-code documentation

    Great job on doing so much in-code commenting. It helps so much when you have to go into code months/years later. I hope you don't mind a couple suggestions.

    If you use XML comments for each method instead of the older style comments, then they can be picked up by code documenting applications as well as intellisense.

    XML documentation MSDN
    XML Documentation Article

    For this piece of code with old school C style comments:
    Code:
            //--------------------------------------------------------------------------------
            // # Name   : ProcessListen
            // # Desc   : Listen to new Clients accsept them and call OnConnect
            // # Status : Finished
            //--------------------------------------------------------------------------------
     
            private void ProcessListen()
            {
                while (m_ListenVar.m_Factor)
                {
                    if (m_Listner.Pending())
                    {
                       TcpClient Client = m_Listner.AcceptTcpClient();
                       OnConnect(Client);
     
                    }
                    // ----
                    Thread.Sleep(m_ListenVar.m_Idle);
                }
            }
    After you have entered the method, go back to the line above (line 6 in this case) and type 3 slashes ///
    Visual Studio will stub in the rest of the comment. Any time you type a < symbol you will see a list of other comment tags you can use, such as the <remarks> tag I put in. You can see that when SomeOtherMethod calls or references the method with the XML tags the description is shown in Intelisense
    [IMGNOTHUMB]http://files.me.com/tlhintoq/xaqj1e[/IMGNOTHUMB]

    Second suggestion: Use #region / #endregion
    #region and #endregion are used to surround a block of code that has a common purpose. The beauty of it is that you can collapse regions just like methods. They keyboard combination of [Control]M [Control]O will collapse the entire document at once. I make it a habit of open a page then collapse it all so I don't have to scroll through meters of code. Just open the region I need, then open the method I need. Its all about keeping organized.
    [IMGNOTHUMB]http://files.me.com/tlhintoq/j61pjn[/IMGNOTHUMB]

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      They keyboard combination of [Control]M [Control]O will collapse the entire document at once.
      Sweet mercy I wish I had known that all a long. I have been doing it by hand.

      As for detecting a discconect, I wrote a function for it.
      Check out this thread:

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        Originally posted by Plater
        Sweet mercy I wish I had known that all a long. I have been doing it by hand.
        [IMGNOTHUMB]http://files.me.com/tlhintoq/6ncs9o[/IMGNOTHUMB]

        Comment

        • NewLegend
          New Member
          • Feb 2010
          • 2

          #5
          tlhintoq big thanks man for the tips i will take them and can you share the style of your visual studio i really like it :)

          Plater big thanks for your function its hellp me alot

          Comment

          • tlhintoq
            Recognized Expert Specialist
            • Mar 2008
            • 3532

            #6
            tlhintoq big thanks man for the tips i will take them and can you share the style of your visual studio i really like it :)
            Its just VS08 running on Windows7 ultimate. I haven't done anything special to it (beyond some tools like nArrange, Dofuscator and ReSharper) but those don't affect the look, just add features.

            Comment

            Working...