Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am working on TcpListener and TcpClient and communicate with each other succsessfully.
I properly closes all objects related to this communication. like in below code:

C#
string mess = "Alert";
                string caption = "Do you want to close Server and stop Application?";
                DialogResult dlgg = MessageBox.Show(caption, mess, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (dlgg == DialogResult.Yes)
                {
                    if (networkStream != null)
                    {
                        networkStream.Close();
                        networkStream.Dispose();
                    }

                    else 
                    {
                       Process currprocess = Process.GetCurrentProcess();
                       currprocess.Kill();
                    }

                    if (this.clientSocket != null)
                    {
                        clientSocket.Close();
                    }
                    else { }

                    this.serverSocket.Stop();
                    
                    msg = "Disconnecting all clients , Server succsessfully Stopped!";
                    message();
                  
                    this.Close();
                    Application.Exit();
                }
                else { }


But sometimes port not closes and it goes in close_wait state (as i found it in cmd.exe using "netstat") so at that time if i again start application and listen to same port client get connected but application says client not connected. and error said "only one usage of each socket is permited". so if i kill process is it good for my application.Or give me suggestions to overcome this error. this is the very important error i need to solve.

thanks.
Posted

The question "is it good" can be understood in different aspects.

"Can something bad happen to an OS or to a communicating application on the other side if I kill some process?"
No. Your application should be able to handle it safely, because such disruptions can always happen in real life. But it depends on how you write it.

"Is it an acceptable programming practice?"
Absolutely not. If you use killing of some process to go out of some difficult situation, consider your project totally failed.

I cannot tell you how you can "fix" your code, because it is probably wrong by design. Please see my past answers; in particular, I described the problem of disconnection:
How Do I Get To Know If A A Tcp Connection Is Over[^],
an amateur question in socket programming[^],
Multple clients from same port Number[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900