我有一个从套接字读取数据的功能。
public int getResp(byte[] Buff, ref int rxBytes)//Buff is byte array of length 150000 bytes
{
while (socet.Available < rxBytes)//rxBytes = 150000
{
int socketAvaildata = socet.Available;
Thread.Sleep(1000);
if (socketAvaildata == socet.Available)
break;
}
try
{
//Thread.Sleep(100);
rxBytes = socet.Available;
if (rxBytes > 0)
{
socet.Receive(Buff, rxBytes, 0);
return rxBytes;
}
}
catch (Exception ex)
{
}
return -1;
}
当我们必须读取小数据时,此功能很好用,但是当我们必须读取大数据(超过100000字节)时,它仅返回部分数据。在dubug模式下,我检查了
break
时控件是否到达socet.Available = 65536
。那么,这是我们可以阅读的最大限制,还是我做错了什么?
最佳答案
Receive
方法返回实际接收的字节数。因此,只需将该位更改为:
rxBytes = socet.Receive(Buff, rxBytes, 0);
return rxBytes;
请注意,
rxBytes
可能少于您最初请求的字节数。为确保您已准确读取该字节数,请使用:public bool TryReadResponse(byte[] buffer, int expectedNumberOfBytes)
{
try
{
int remaining = expectedNumberOfBytes;
int offset = 0;
while (remaining > 0)
{
int read = socet.Receive(buffer, offset, remaining, SocketFlags.None);
if (read == 0)
{
// other side has closed the connection before sending the requested number of bytes
return false;
}
offset += read;
remaining -= read;
}
return true;
}
catch (Exception ex)
{
// failure
return false;
}
}
我很乐意从参数中删除
ref
,因为您只对操作是否完全成功感兴趣。
关于c# - 通过套接字读取的最大数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548744/