C#套接字接收字节数组长度 [英] c# socket receive byte array length
问题描述
我正在尝试学习在C#中使用套接字,我对此表示怀疑,我正在使用类似以下的代码:
i'm trying to learn to use sockets in c# and i've a doubt, i'm using a code something like this:
byte[] data = new byte[64];
int length = 0;
length = sock.Receive(data);
//more code...
因此,byte[]
数据填充有接收到的数据,数组的左侧空间填充了0s,byte[]
是否已完全分配到内存中(全部64个字节)?如果是这样,是否有办法使byte[]
的大小与实际发送的数据相同?
So, the byte[]
data is filled with the recived data and the left space in the array is filled with 0s, Is the byte[]
allocated into memory completely (all 64bytes)? If it's so, is there a way to make the byte[]
the same size as the actual sent data?
推荐答案
您可以检查sock.Available
来查看已包含的内容.(到目前为止)
You can check sock.Available
to see what has already come in. (so far)
byte[] data = new byte[sock.Available];
int length = sock.Receive(data);
//more code...
注意:由于您可能知道或可能不知道网络接下来会发生什么,因此通常更有意义的做法是先只读取一个标头(带有大小信息),或者分配超出必要的空间,然后多次调用.Recieve()
直到达到记录结束的时间.
Note: Since you may or may not know what is coming in next on the network it usually makes more sense to read only a header (with size info) first or to allocate more space than necessary, and call .Recieve()
multiple times until the end of a record is reached.
注意:此代码假定您已经知道要接收一些数据,并且已经等待了足够长的时间以准备一些有用的数据.
Note: This code assumes you already know there is some data to receive and you've waited long enough for some useful amount of data to be ready.
如果确实选择使用长度标题,则.Available
可以帮助您避免读取部分标题,而不必重新组装它,这很好. (在这种情况下,只有大邮件可能需要手动重组)
If you do choose to use length headers, .Available
can help you avoid reading a partial header and having to re-assemble it which is nice. (Only large messages may need manual reassembly in that case)
这篇关于C#套接字接收字节数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!