I have a created a multi-threaded TcpClient server that works for my needs. Each thread uses synchronous (blocked) communication to wait for a command from the client
Here's the problem...if a client does not gracefully disconnect (unplug the device from the network or a power failure), my server does not recognize the lost connection and just continues to wait to receive data.
Any help would be great, I have been searching online for a few days now and I know I'm doing everything correctly except this problem.
Thank you in advance.
Here is a new Thread of the server that to receives the data:
class ConnectionThread
{
public TcpListener threadListener;
private static int connections = 0;
public event textParserEventHandler incomingText;
public void HandleConnection()
{
int recv;
byte[] data = new byte[1024];
string foundText = null;
string[] textList = null;
TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
textParserEventArgs e = new textParserEventArgs(ns);
while (true)
{
try
{
data.Initialize();
//*** Waits on next line for data, returns 0 if graceful disconnect ***///
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
foundText = Encoding.ASCII.GetString(data, 0, recv);
textList = foundText.Split(' ');
e.foundText = textList;
incomingText(this, e);
}
catch (System.IO.IOException f)
{
Console.WriteLine("Data Read Error: " + f.Message);
}
}
ns.WriteTimeout = 1;
client.LingerState.Enabled = false;
ns.Close();
client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
Thread.CurrentThread.Abort();
}
}