UDPClient只接收一个数据报

时间:2011-03-29 05:42:47

标签: c# udp

我正在尝试读取连续的UDP字节(或者一次至少读取1个以上)。我的缓冲区大小是单个数据报/数据包(1000字节)的4倍。

 Byte[] receiveBytes = new Byte[4096];

 UdpClient udpClient = new UdpClient(56885);
 IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
 Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);

2 个答案:

答案 0 :(得分:3)

Receive method一次只能读取一个数据报包。如果您想要阅读多个数据报,则需要多次调用Receive

答案 1 :(得分:0)

如果要接收多个数据包,则应考虑使用异步方法接收它们。 UdpClient类有一个异步惯用法,你给它一个回调函数,然后继续进行其他处理(比如更新UI)。

Here is an example from the source:

public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
{
  UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
  IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

  Byte[] receiveBytes = u.EndReceive(ar, ref e);
  string receiveString = Encoding.ASCII.GetString(receiveBytes);

  Console.WriteLine("Received: {0}", receiveString);
  messageReceived = true;
}

public static void ReceiveMessages()
{
  // Receive a message and write it to the console.
  IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
  UdpClient u = new UdpClient(e);

  UdpState s = new UdpState();
  s.e = e;
  s.u = u;

  Console.WriteLine("listening for messages");
  u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

  // Do some work while we wait for a message. For this example, 
  // we'll just sleep 
  while (!messageReceived)
  {
    Thread.Sleep(100);
  }
}