I am very new to c# so please bear with me.

My goal is to make a simple tcp chat server and client to get used to c# sockets a bit more. I do have experience with sockets so I thought this was a good place to start.

The code I currently have works fine while it is running. The client closes fine. The server closes fine as long as a client hasn't connected. If a client connects and disconnects, then the server tries to close, the server GUI will close, but the process is still open. This leads me to believe that either a thread has been left open or some sockets have been left open. My best guess on the location of the error is the KeepListening thread in ChatServer, but I can't be sure.

Declare volatile boolean varible to control the thread.

volatile bool ServRunning = false;

Check for pending request,

private void KeepListening()
{
   //While the server is running
    while(ServRunning == true){
     try
	{
          //Accept a pending connection
          if (tlsClient.Pending()){
                        tcpClient = tlsClient.AcceptTcpClient();
                        //Create a new instance of Connection
                        Connection newConnection = new Connection(tcpClient);
           }
	}catch(SocketException)
	{
	  ;//Do Nothing
	}
     }
  }
}

You could add stop method in CharServer class.

public void Stop() { ServRunning = false; }

Finally, have a look at UI,

// declare an object varible of ChatServer 
ChatServer mainServer;

protected override void Dispose(bool disposing)
{
    if(mainServer!=null)    
            mainServer.Stop();
   if (disposing) {
       if (components != null) {
	 components.Dispose();
	}
    }
   base.Dispose(disposing);
}

Thank you for the quick reply, but the program is still not closing properly. I think you are trying to close the KeepListening thread, but I would like to know exactly what you are trying to fix so I can learn from this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.