声明一个长度为2M的数组,但是我只需要保留5K,如何获得真正的价值? [英] Declare an array of length 2M, but I have to just keep 5K, how to get inside the real value?
本文介绍了声明一个长度为2M的数组,但是我只需要保留5K,如何获得真正的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
string[] splitString = client.Client.LocalEndPoint.ToString().Split(':');
IPEndPoint local = new IPEndPoint(IPAddress.Parse(splitString[0]),Int32.Parse(splitString[1]));
receiveUDPClient = new UdpClient(local);
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
int recAllLength = 0;
while (true)
{
try
{
byte[] receiveBytes= new Byte[1024 * 1024 * 2];
byte[] arr=new byte[1024*5];
arr = receiveUDPClient.Receive(ref remote);
Buffer.BlockCopy(arr, 0, receiveBytes, 0, arr.Length);
int recLength = receiveBytes.Length;//debugs says recLength=1024*1024*2
// MessageBox.Show(recLength.ToString()+","+arr.Length);
while (arr.ToString() != "over")
{
arr= receiveUDPClient.Receive(ref remote);
MessageBox.Show(arr.Length.ToString());
if (arr.ToString().Contains("over,"))
{
string[] splitstring = arr.ToString().Split(',');
recAllLength = Int32.Parse(splitstring[1]);
//I want to get the real length,but actually it is the entire length of the array, not the length of valid data
break;
}
MessageBox.Show(recLength.ToString() + "," + arr.Length.ToString());
//debugs Exception,Array bounds because reclength=1024*1024*2;
Buffer.BlockCopy(arr, 0, receiveBytes,recLength,arr.Length );
// arr = null;
recLength += arr.Length;
}
MessageBox.Show(recLength.ToString());
现在receiveBytes里面的值的长度为5 * 1024,但实际上可能小于5 * 1024的长度,如果循环接收,将不会获得真实值,而后如何获得接收器的真实长度arr?
debug说recLength = 1024 * 2 * 1024,但是实际上它可以小于5 * 1024,我如何才能获得真正的Reclength?
Now receiveBytes inside length of the value of 5 * 1024, but in fact may be less than the length of 5 * 1024, if the loop receiver, will not get the true value, and how do I get the true length of the receiver after the arr?
debug says recLength=1024*2*1024,but in fact it can be less than 5*1024,how can I get the real reclength?
推荐答案
而不是初始化arr
达到某个大小,让Receive
方法返回一个Byte
数组,此时,arr.Length
应该具有要复制的缓冲区的大小.
Instead of initializingarr
to a certain size, let theReceive
method return aByte
array, and at that point,arr.Length
should have the size of the buffer being copied.
这篇关于声明一个长度为2M的数组,但是我只需要保留5K,如何获得真正的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文