The code below has a StreamReader read from a network stream. This code will work fine for several days. I ran into a problem when suddenly StreamReader.ReadLine () started returning null.
According to the documentation of Microsoft StreamReader.ReadLine () will return null when it reaches the end of the input stream. This does not make sense to me when the underlying stream is NetworkStream. Should ReadLine () not be blocked until the network stream receives data?
This is the first time I have encountered this problem and I have not been able to duplicate it. What could be the reason for this?
Context: An application receives CDRs from a telephone switch. The phone switch connects to the application and sends plain old text entries. After the switch is connected, it will remain connected and will continue to send records for eternity if something does not break.
private void ProcessClient(TcpClient client)
{
try
{
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
while (m_RunService & client.Connected)
{
string curLine = reader.ReadLine();
}
}
}
}
catch (Exception ex)
{
}
}
Here is the code that starts the listener:
private void Listen()
{
try
{
while (m_RunService)
{
try
{
m_TcpClient = m_TcpListener.AcceptTcpClient();
ProcessClient(m_TcpClient);
}
catch (Exception ex)
{
}
finally
{
m_TcpClient.Close();
}
}
}
finally
{
m_TcpListener.Stop();
}
}
source
share