Home > database >  C# TCP listener not catching exception
C# TCP listener not catching exception

Time:12-30

I have the following configuration for the server, that connects successfully to the client and runs the following threads.

My issue is when the client disconnects, it doesn't catch the exception:

private void Form1_Load(object sender, EventArgs e)
{
   th_StartListen = new Thread(new ThreadStart(StartListen));
   th_StartListen.Start();
   txtCmdOutput.Focus();
}

private void StartListen()
{
    //Creating a TCP Connection and listening to the port
    tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
    tcpListener.Start();
    toolStripStatusLabel1.Text = "Listening on port 6666 ...";
    int counter = 0;
    appStatus = 0;
 
    while (true)
    {
        try
        {
            client = tcpListener.AcceptTcpClient();
            counter  ;
            clientList.Add(client);
            var ipend = (IPEndPoint)client.Client.RemoteEndPoint;

            //Updating status of connection
            toolStripStatusLabel1.Text = "Connected from "   ipend.Address.ToString();
            appStatus = 1;

            th_inPutStream = new Thread(() => outPutStream(client));
            th_inPutStream.Start();

            th_inPutStream = new Thread(() => inPutStream(client));
            th_inPutStream.Start();
        }
        catch (Exception err)
        {
             Cleanup();
        }
    }
}

It simply loops back and stops at client = tcpListener.AcceptTcpClient(); .

Would appreciate some ideas behind this.

Thanks!

CodePudding user response:

Look carefully at your logic. Since both input stream and output stream are running on separate threads, the code will continue executing after starting the second thread, and when it does so, it will loop around, hit the true condition, and then start listening for a new client connection immediately.

Your exception isn't being caught because you're not generating an exception. A client closing it's connection to the server isn't necessarily an exception generating event.

  • Related