In the code below I have a StreamReader reading from a network stream. This code normally will run fine for days. I ran into a problem where all of a sudden StreamReader.ReadLine() started returning null.
According to Microsoft documentation StreamReader.ReadLine() will return null when it has reached the end of the input stream. This doesn't make sense to me when the underlying stream is a NetworkStream. Shouldn't ReadLine() just block until the network stream receives data?
This is the first time I ran into this problem and I have not been able to duplicate it. What could cause this?
Context: the application receives CDR records from a phone switch. The phone switch connects to the application and sends plain old text records. After the switch connects it will remain connected and keep sending records for eternity unless something breaks.
private void ProcessClient(TcpClient client)
{
try
{
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
//continue processing while service is on
while (m_RunService & client.Connected)
{
string curLine = reader.ReadLine();
//code here does stuff to string
//will catch any exceptions that have to do with
//processing the string
}
}
}
}
catch (Exception ex)
{
//write to log
}
}
Here is the code that starts the listener:
private void Listen()
{
try
{
while (m_RunService)
{
try
{
m_TcpClient = m_TcpListener.AcceptTcpClient();
//run on same thread, should only ever be 1 cnx at a time
ProcessClient(m_TcpClient);
}
catch (Exception ex)
{
//write to log
}
finally
{
m_TcpClient.Close();
}
}
}
finally
{
m_TcpListener.Stop();
}
}