473,396 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

[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

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.  
Feb 8 '10 #1

✓ answered 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

5 2323
tlhintoq
3,525 Expert 2GB
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.

Feb 8 '10 #2
Plater
7,872 Expert 4TB
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
Feb 8 '10 #3
tlhintoq
3,525 Expert 2GB
Sweet mercy I wish I had known that all a long. I have been doing it by hand.

Feb 8 '10 #4
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
Feb 8 '10 #5
tlhintoq
3,525 Expert 2GB
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.
Feb 8 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: William | last post by:
My company produces 2 versions of our program. One is a 32 bit VB created in VB 6. The other is an ASP based Web app. The reason the Web app was created was to address client useage where the...
0
by: elcc1958 | last post by:
I need to support a VB6 application that will be receiving disconnected ADODB.Recordset from out DotNet solution. Our dotnet solution deals with System.Data.DataTable. I need to populate a...
11
by: Philip Germanos | last post by:
Hello. I have a project which consists of developing an application for pocket pc's. Briefly the client application which is a medical application for pharmacists will have to access a database...
5
by: Morten | last post by:
How do I detect if a client socket is no longer connected to the listen tcp socket ? I have tried with (just an example): --------------------- Socket tcpSocket; ...
30
by: DJ van Vliet | last post by:
Hi All, Question regarding the processes between C#, ADO.NET and MS-SQL I need to understand the complexities of using the distributed method (ADO.NET) of data retrieval and the subsequent...
22
by: Jordan S. | last post by:
SQL Server will be used as the back-end database to a non trivial client application. In question is the choice of client application: I need to be able to speak intelligently about when one...
0
by: khu84 | last post by:
Here is client server very simple code, seems to work with telnet but with with web client code gives blank output. Following is the server code:- <?php function...
1
by: Miroslav Endys | last post by:
I have two apps. Client and Server (both are windows console apps). Im using Client Socket of this definition AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp and Im using async...
5
by: tichi | last post by:
I'm writing a program that in its most simplest form acts as a proxy between a local client and a remote server. But I cannot figure out how to detect when either the connection to the client is...
7
by: Vishal | last post by:
Hi, I am writing a CGI to serve files to the caller. I was wondering if there is any way to tell in my CGI if the client browser is still connected. If it is not, i want to execute some special...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.