1

I have a fairly simple client/server architecture using TCP client. The server is set up to close connections from clients it hasn't received a message from in two minutes. I have verified that this works fine using a C++ TCP client for my Android device. However, my C# client always appears to be connected, even after the server closes the connection.

I've tried a variety of things and none of them seem to accurately report that the connection has been closed. TcpClient.Connected always returns true, even after sending and receiving messages, unlike what is specified in the MSDN documentation. C# Client code:

var client = new TcpClient(server, port);
var stream = client.GetStream();

//Wait >2 mins to get disconnected
await Task.Delay(Timespan.FromMinutes(2.5));

void Write()
{
    try
    {
        var data = BuildByteArrayFromMyData();
        stream.Write(data , 0, data.Length);

        if(!client.Connected)
        {
            //Never triggered, Connected always equals true
        }
    }

    catch(Exception ex)
    {
        //Never triggered
    }
}

void ReadOnAnotherThread()
{
    while (true)
    {
        try
        {
            while (!stream.DataAvailable)
            {
                if (!client.Connected) break; //Never triggered, Connected always equals true
                else await Task.Delay(TimeSpan.FromMilliseconds(11));
            }

            byte[] data = new byte[];
            int bytes = stream.Read(data, 0, data.Length);
         }
    }

    catch(Exception ex)
    {
        //Never triggered
    }
}

Q: What is the correct way to use TcpClient.Connected?


Similar questions that do NOT answer the question proposed here:


lolcodez
  • 559
  • 1
  • 8
  • 16
  • the code you added doesn't make much sense...I don't see you closing the connection like you claim you do – Leo Oct 23 '14 at 01:49
  • This is the client code. The connection is closed by the server. – lolcodez Oct 23 '14 at 01:50
  • 9
    There is no correct way to use `TcpClient.Connected`. It's a very misleading property name, which should actually be called `TcpClient.UsedToBeConnectedAtSomePointInThePastAndAsFarAsIKnowItStillIsButImNotSure`. In other words, it's practically useless. To detect dropped connections, the best option is to send data at regular intervals, as I [describe on my blog](http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html). – Stephen Cleary Oct 23 '14 at 12:20

0 Answers0