为什么streamreader连接到网络流在ReadLine()上返回null?
在下面的代码中,我有一个从网络流中读取的StreamReader。 这段代码通常可以运行好几天。 我遇到了一个问题,突然StreamReader.ReadLine()开始返回null。
根据Microsoft文档,StreamReader.ReadLine()在到达输入流的末尾时将返回null。 当底层流是NetworkStream时,这对我没有意义。 ReadLine()不应该阻塞直到网络流接收数据?
这是我第一次遇到这个问题而我无法复制它。 什么可能导致这个?
背景信息:应用程序从电话交换机接收CDR记录。 电话交换机连接到应用程序并发送普通的旧文本记录。 在交换机连接后,它将保持连接并继续发送永久记录,除非出现故障。
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 } }
以下是启动侦听器的代码:
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(); } }
StreamReader
将阻塞,直到它接收数据或连接关闭。 这听起来像是在服务器端发生的exception,它关闭了连接,而客户端没有收到任何数据。
这几乎听起来就像流已经关闭了。 否则是:它会阻止。 我的猜测:网络#fail
如果NetworkStream
没有可用数据,则对ReadLine()
的调用将返回null,因为它假定它已到达流的末尾。
在调用ReadLine
之前,请尝试检查NetworkStream.CanRead
和NetworkStream.DataAvailable
。 如果连接尚未关闭,请手动阻止一段时间,然后再次尝试阅读。
编辑您可以通过Send
或使用底层Socket
来检查连接是否仍处于打开状态:
Connected属性获取最后一次I / O操作时Socket的连接状态。 当它返回false时,Socket从未连接,或者不再连接。
Connected属性的值反映了最近操作时的连接状态。 如果需要确定连接的当前状态,请进行非阻塞,零字节发送调用。 如果调用成功返回或抛出WAEWOULDBLOCK错误代码(10035),则套接字仍然连接; 否则,套接字不再连接。