Connect with Expertise | Find Experts, Get Answers, Share Insights

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

 
Join Date: Feb 2010
Posts: 2
#1: Feb 8 '10
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

Expand|Select|Wrap|Line Numbers
  1. public class NetCore
  2.     {
  3.         private int             MAX_CONNECTIONS = Settings.Default.MAX_CONNECTIONS;
  4.         // ----
  5.  
  6.         public int              m_Port;
  7.         public int              m_ActiveClients;
  8.         public int              i;
  9.         public TcpClient[]         m_Coneections;
  10.  
  11.         // ----
  12.         private TcpListener     m_Listner;
  13.         private ProcessVar      m_ListenVar;
  14.         private ProcessVar      m_PacketVar;
  15.  
  16.         // ----
  17.         public NetCore(int iPort)
  18.         {
  19.             m_Port = iPort;
  20.             // ----
  21.             m_Coneections = new TcpClient[MAX_CONNECTIONS];
  22.             m_ActiveClients = 0;
  23.             // ----
  24.             m_ListenVar.m_Thread = new Thread(ProcessListen);
  25.             m_PacketVar.m_Thread = new Thread(ProcessPacket);
  26.             // ----
  27.             m_ListenVar.m_Idle = 1000;
  28.             m_PacketVar.m_Idle = 1;
  29.         }
  30.         //--------------------------------------------------------------------------------
  31.         // # Name   : ProcessListen
  32.         // # Desc   : Listen to new Clients accsept them and call OnConnect
  33.         // # Status : Finished
  34.         //--------------------------------------------------------------------------------
  35.  
  36.         private void ProcessListen()
  37.         {
  38.             while (m_ListenVar.m_Factor)
  39.             {
  40.                 if (m_Listner.Pending())
  41.                 {
  42.                    TcpClient Client = m_Listner.AcceptTcpClient();
  43.                    OnConnect(Client);
  44.  
  45.                 }
  46.                 // ----
  47.                 Thread.Sleep(m_ListenVar.m_Idle);
  48.             }
  49.         }
  50.  
  51.         //--------------------------------------------------------------------------------
  52.         // # Name   : ProcessPacket
  53.         // # Desc   : get the packets and check if connection still alive
  54.         // # Status : not found yet if client is connected or not
  55.         //--------------------------------------------------------------------------------
  56.  
  57.         private void ProcessPacket()
  58.         {
  59.             byte[] Recv;
  60.             // --------
  61.             while (m_PacketVar.m_Factor)
  62.             {
  63.                 if (m_ActiveClients > 0)
  64.                 {
  65.                     for (i = 0; i != m_ActiveClients; i++)
  66.                     {
  67.                         try
  68.                         {
  69.                             if (m_Coneections[i].Available > 0)
  70.                             {
  71.                                 Recv = new byte[m_Coneections[i].Available];
  72.                                 int ret = m_Coneections[i].Client.Receive(Recv, Recv.Length, );
  73.                                 // ---
  74.                                 if (ret > 0)
  75.                                 {
  76.                                     OnRecv(m_Coneections[i], Recv);
  77.                                 }
  78.                                 else
  79.                                 {
  80.                                     OnDisconnect(m_Coneections[i]);
  81.                                 }
  82.                             }
  83.                             else if (!m_Coneections[i].Connected)
  84.                             {
  85.                                 // ---
  86.                                 OnDisconnect(m_Coneections[i]);
  87.                                 continue;
  88.                             }
  89.                         }
  90.                         catch (Exception x)
  91.                         {
  92.  
  93.                             OnDisconnect(m_Coneections[i]);
  94.                         }
  95.                     }
  96.                 }
  97.                 // ----
  98.                 Thread.Sleep(m_PacketVar.m_Idle);
  99.             }
  100.         }
  101.  
  102.         //--------------------------------------------------------------------------------
  103.  
  104.         public bool Create()
  105.         {
  106.             bool bResult = true;
  107.             try
  108.             {
  109.                 // ----
  110.                 m_Listner = new TcpListener(IPAddress.Any, m_Port);
  111.                 m_Listner.Start();
  112.                 // -----
  113.                 m_ListenVar.m_Factor = true;
  114.                 m_ListenVar.m_Thread.Start();
  115.                 // -----
  116.                 m_PacketVar.m_Factor = true;
  117.                 m_PacketVar.m_Thread.Start();
  118.                 // ----
  119.                 OnCreate();
  120.                 // -----
  121.                 bResult = true;
  122.             }
  123.             catch (Exception x)
  124.             {
  125.                 OnCreate(x);
  126.                 // -----
  127.                 bResult = false;
  128.             }
  129.             // -----
  130.             return bResult;
  131.         }
  132.         //--------------------------------------------------------------------------------
  133.  
  134.         public void Close()
  135.         {
  136.             OnClose();
  137.         }
  138.  
  139.         //--------------------------------------------------------------------------------
  140.  
  141.         public virtual void OnConnect(TcpClient uClient)
  142.         {
  143.             m_Coneections[m_ActiveClients] = uClient;
  144.             m_ActiveClients++;
  145.         }
  146.         //--------------------------------------------------------------------------------
  147.  
  148.         public virtual void OnDisconnect(TcpClient uClient)
  149.         {
  150.             m_ActiveClients--;
  151.         }
  152.         //--------------------------------------------------------------------------------
  153.  
  154.         public virtual void OnRecv(TcpClient uClient, byte[] bRecvBytes)
  155.         {
  156.  
  157.         }
  158.         public virtual void OnClose()
  159.         {
  160.             for (i = 0; i != m_ActiveClients; i++)
  161.             {
  162.                 m_Coneections[i].Close();
  163.             }
  164.             // -----
  165.             m_ListenVar.m_Factor = false;
  166.             m_ListenVar.m_Thread.Abort();
  167.             // -----
  168.             m_PacketVar.m_Factor = false;
  169.             m_PacketVar.m_Thread.Abort();
  170.             // -----
  171.             m_ActiveClients = 0;
  172.         }
  173.         //--------------------------------------------------------------------------------
  174.  
  175.         public virtual void OnCreate()
  176.         {
  177.  
  178.         }
  179.         //--------------------------------------------------------------------------------
  180.  
  181.         public virtual void OnCreate(Exception x)
  182.         {
  183.  
  184.         }
  185.  
  186.         //--------------------------------------------------------------------------------
  187.  
  188.         private struct ProcessVar
  189.         {
  190.             public Thread  m_Thread;
  191.             public bool m_Factor;
  192.             public int m_Idle;
  193.  
  194.         }
  195.     }
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






Expand|Select|Wrap|Line Numbers
  1.     //--------------------------------------------------------------------------------
  2.  
  3.     public class StateObject
  4.     {
  5.         public Socket workSocket        = null;
  6.         public const int BufferSize     = 1024;
  7.         public byte[] buffer            = new byte[BufferSize];
  8.         public StringBuilder sb         = new StringBuilder();
  9.     }
  10.  
  11.     //--------------------------------------------------------------------------------
  12.     public class NetCore
  13.     {
  14.         // ------
  15.         public int                  m_Port;
  16.         public int                  m_maxQueue;
  17.         // ------
  18.         private Socket              m_Listner;
  19.         private IPEndPoint          m_LocalEPoint;
  20.         private ProcessVar          m_ListenVar;
  21.         private ManualResetEvent    m_allDone;
  22.         // ------
  23.         private int                 m_iTemp;
  24.  
  25.         //--------------------------------------------------------------------------------
  26.  
  27.         public NetCore(int iPort)
  28.         {
  29.  
  30.             // ----
  31.             m_Port = iPort;
  32.             // ----
  33.             m_LocalEPoint = new IPEndPoint(IPAddress.Any, m_Port);
  34.             m_Listner = new Socket(m_LocalEPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  35.             m_allDone = new ManualResetEvent(false);
  36.             // ----
  37.             m_ListenVar.m_Thread = new Thread(ProcessListen);
  38.             //m_PacketVar.m_Thread = new Thread(ProcessPacket);
  39.             // ----
  40.             m_ListenVar.m_Idle = 1000;
  41.             //m_PacketVar.m_Idle = 1;
  42.         }
  43.         //--------------------------------------------------------------------------------
  44.         // # Name   : Create
  45.         // # Desc   : Create the Listen Process , etc..
  46.         // # Status : --
  47.         //--------------------------------------------------------------------------------
  48.  
  49.         public bool Create()
  50.         {
  51.             bool bReturn = false;
  52.             // ------
  53.             try
  54.             {
  55.                 // ------
  56.                 m_Listner.Bind(m_LocalEPoint);
  57.                 m_Listner.Listen(m_maxQueue);
  58.                 // ------
  59.                 m_ListenVar.m_Factor = true;
  60.                 m_ListenVar.m_Thread.Start();
  61.                 // ------
  62.                 OnCreate();
  63.                 // ------
  64.                 bReturn = true;
  65.             }
  66.             catch (SocketException x)
  67.             {
  68.                 OnCreate(x);
  69.                 bReturn = false;
  70.             }
  71.  
  72.             // ------
  73.             return bReturn;
  74.         }
  75.         //--------------------------------------------------------------------------------
  76.         // # Name   : Close
  77.         // # Desc   : --
  78.         // # Status : --
  79.         //--------------------------------------------------------------------------------
  80.  
  81.         public void Close()
  82.         {
  83.         }
  84.         //--------------------------------------------------------------------------------
  85.         // # Name   : ProcessListen
  86.         // # Desc   : Listen to new Clients accsept them and call OnConnect
  87.         // # Status : Finished
  88.         //--------------------------------------------------------------------------------
  89.  
  90.         private void ProcessListen()
  91.         {
  92.             while (m_ListenVar.m_Factor)
  93.             {
  94.                 m_allDone.Reset();
  95.  
  96.                 m_Listner.BeginAccept(new AsyncCallback(ProcessAccept), m_Listner);
  97.  
  98.                 m_allDone.WaitOne();
  99.             }
  100.         }
  101.         //--------------------------------------------------------------------------------
  102.  
  103.         private void ProcessAccept(IAsyncResult SyncResult)
  104.         {
  105.             m_allDone.Set();
  106.  
  107.             Socket Listener = (Socket)SyncResult.AsyncState;
  108.             Socket Handler = Listener.EndAccept(SyncResult);
  109.  
  110.             OnConnect(Handler);
  111.  
  112.             StateObject StateObj = new StateObject();
  113.             StateObj.workSocket = Handler;
  114.  
  115.             Handler.BeginReceive(StateObj.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ProcessRecv), StateObj);
  116.         }
  117.         //--------------------------------------------------------------------------------
  118.  
  119.         private void ProcessRecv(IAsyncResult SyncResult)
  120.         {
  121.             StateObject StateObj = (StateObject)SyncResult.AsyncState;
  122.             Socket Handler = StateObj.workSocket;
  123.  
  124.             m_iTemp = Handler.EndReceive(SyncResult);
  125.  
  126.             if (m_iTemp > 0)
  127.             {
  128.                 OnRecv(StateObj.buffer, Handler);
  129.             }
  130.  
  131.  
  132.         }
  133.         //--------------------------------------------------------------------------------
  134.  
  135.         public virtual void OnCreate()
  136.         {
  137.  
  138.         }
  139.         //--------------------------------------------------------------------------------
  140.  
  141.         public virtual void OnCreate(SocketException x)
  142.         {
  143.  
  144.         }
  145.         //--------------------------------------------------------------------------------
  146.  
  147.         public virtual void OnConnect(Socket Client)
  148.         {
  149.  
  150.         }
  151.         //--------------------------------------------------------------------------------
  152.  
  153.         public virtual void OnDisconnect(Socket Client)
  154.         {
  155.  
  156.         }
  157.         //--------------------------------------------------------------------------------
  158.  
  159.         public virtual void OnRecv(byte[] buffer, Socket Client)
  160.         {
  161.  
  162.         }
  163.         //--------------------------------------------------------------------------------
  164.  
  165.         private struct ProcessVar
  166.         {
  167.             public Thread m_Thread;
  168.             public bool m_Factor;
  169.             public int m_Idle;
  170.  
  171.         }
  172.  
  173.  
best answer - posted by Plater
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:
http://bytes.com/topic/c-sharp/answe...nnected-status

tlhintoq's Avatar
E
C
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 3,476
#2: Feb 8 '10

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


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:
Expand|Select|Wrap|Line Numbers
  1.         //--------------------------------------------------------------------------------
  2.         // # Name   : ProcessListen
  3.         // # Desc   : Listen to new Clients accsept them and call OnConnect
  4.         // # Status : Finished
  5.         //--------------------------------------------------------------------------------
  6.  
  7.         private void ProcessListen()
  8.         {
  9.             while (m_ListenVar.m_Factor)
  10.             {
  11.                 if (m_Listner.Pending())
  12.                 {
  13.                    TcpClient Client = m_Listner.AcceptTcpClient();
  14.                    OnConnect(Client);
  15.  
  16.                 }
  17.                 // ----
  18.                 Thread.Sleep(m_ListenVar.m_Idle);
  19.             }
  20.         }
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



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.

Plater's Avatar
E
M
C
 
Join Date: Apr 2007
Location: New England
Posts: 7,463
#3: Feb 8 '10

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


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:
http://bytes.com/topic/c-sharp/answe...nnected-status
tlhintoq's Avatar
E
C
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 3,476
#4: Feb 8 '10

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


Sweet mercy I wish I had known that all a long. I have been doing it by hand.

 
Join Date: Feb 2010
Posts: 2
#5: Feb 8 '10

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


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
tlhintoq's Avatar
E
C
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 3,476
#6: Feb 8 '10

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


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.
Reply