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: