2011-03-29 64 views
1

我試圖讀取連續的UDP字節(或一次至少超過1個)。我的緩衝區是單個數據報/數據包(1000字節)的4倍大小。UDPClient只接收一個數據報

Byte[] receiveBytes = new Byte[4096]; 

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

多少數據你送?你發送的速率是多少? – Jeff 2011-03-29 05:50:28

回答

3

Receive method將只讀取一次一個報包。如果您想要讀取多個數據報,您需要多次撥打Receive

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); 
    } 
}