【发布时间】:2023-03-30 05:48:02
【问题描述】:
我有这个ReadAllBytes 方法,它应该读取一定数量
来自NetworkStream的字节数
private void ReadAllBytes(byte[] buffer, int length)
{
if (buffer.Length != length)
throw new Exception("WriteBytes: Length should be same");
Stream stm = m_client.GetStream();
// Start reading
int offset = 0;
int remaining = length;
while (remaining > 0)
{
int read = stm.Read(buffer, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("ReadAllBytes: End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
问题是它在大多数情况下都有效,但有时当程序进入这个函数时,它永远不会返回并且似乎永远运行。我使用日志记录发现了这一点。我像这样使用它:
public TcpClient m_client = new TcpClient();
m_client.Connect(IP,port);
ReadAllBytes(lengthArray, 2);
有人可以帮我解决问题吗?我认为这与超时有关,但如何确定呢?以及如何解决这个问题?
这可能与我如何处理这个类有关吗?
我也没有遇到任何异常。
【问题讨论】:
-
网络流大小超过长度时报错?
-
如果长度应该相等,为什么还要添加参数
length?只需使用buffer.Length。 -
lengthArray 是什么?
-
@amitdayama:只是一个字节数组
-
"但是什么会导致它无限期地等待?"没有足够的字节进入。这是 Read 阻塞的唯一原因。找出为什么没有足够的字节。提供的信息无法回答问题。
标签: c# .net networking