我正在使用System.Net.Sockets Socket类接收UDP数据报.我想知道收到的数据报的确切长度,以便检查数据报的有效性.
Socket.Receive(Byte()) 方法文档说:
如果您使用的是无连接套接字,则Receive将从您在Connect方法中指定的目标地址读取第一个排队的数据报.如果您收到的数据报大于缓冲区参数的大小,缓冲区将填充消息的第一部分,多余的数据将丢失并抛出SocketException.
Socket.Available property给出了可读取的字节总数,这是所有排队数据报的大小总和.
有没有办法可以找出下一个数据报的大小?
public static void Receive()
{
Byte[] buf, discardbuf;
const int paklen = 32; //correct packet length
int l;
buf = new Byte[paklen];
discardbuf = new Byte[4096];
while (rcv_enable)
{
l = soc.Available;
if (l == 0) continue;
if (l == paklen) soc.Receive(buf); //receive the correct packet
else soc.Receive(discardbuf); //discard otherwise
Thread.Sleep(200);
Console.WriteLine("Received {0}", l);
};
}
Run Code Online (Sandbox Code Playgroud)