2016-06-07 115 views
0

我正在使用下面的代碼來接收消息(我正在使用這種方式,因爲我正在等待消息時做某事)但是,我正在測試這個連接,並且我發送的消息非常接近彼此,但似乎其中一個失去了。我不知道如何解決這個問題。我怎樣才能啓用「讀取緩衝區」選項或類似的東西?異步Udp消息的緩衝區

感謝..這裏是代碼:

//函數接收UDP消息

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 IpEndPoint_groupEP); 
     received_data_from_client = Encoding.ASCII.GetString(receiveBytes); 
     messageReceived = true; 
     Logger("Received a message from : " + IpEndPoint_groupEP.ToString()); 
     u.Close(); 
    } 

    public static void ReceiveMessages() 
    { 

     IpEndPoint_groupEP.Address = (IPAddress.Any); 
     IpEndPoint_groupEP.Port = listenPort; 

     //IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort); 

     UdpClient u = new UdpClient(IpEndPoint_groupEP); 

     UdpState s = new UdpState(); 

     s.e = IpEndPoint_groupEP; 
     s.u = u; 

     u.BeginReceive(new AsyncCallback(ReceiveCallback), s); 

    while (!messageReceived) 
      { 
        Thread.Sleep(50); 
Console.writeLine("Hello") 


} 

我有u.close因爲這個函數被調用超過一個。我有一個while循環,所以程序讀取消息並對消息做些什麼,然後當它完成時,循環返回並調用ReceiveMessages函數開始讀取另一條消息。基本上,當程序沒有收到消息時,它大喊'你好'

它的工作就像一個魅力。不過,我意識到,當兩個或更多的消息同時到達,它只是讀其中之一,我失去了其他的

+1

你在'ReceiveCallback'中執行'u.Close()',你爲什麼期望它能夠多次運行? –

+0

對不起,我剛剛更新.. – George

回答

1

問題是你關閉消息之間的端口。相反,這樣做移動以外的端口建立的ReceiveMessages()

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 IpEndPoint_groupEP); 
    received_data_from_client = Encoding.ASCII.GetString(receiveBytes); 
    messageReceived = true; 
    Logger("Received a message from : " + IpEndPoint_groupEP.ToString()); 
} 

public static UdpClient CreateClient() 
{ 
    IpEndPoint_groupEP.Address = (IPAddress.Any); 
    IpEndPoint_groupEP.Port = listenPort; 

    UdpClient u = new UdpClient(IpEndPoint_groupEP); 
    return u; 
} 

public static void ReceiveMessages(UdpClient u) 
{ 

    UdpState s = new UdpState(); 

    s.e = IpEndPoint_groupEP; 
    s.u = u; 

    u.BeginReceive(new AsyncCallback(ReceiveCallback), s); 

    while (!messageReceived) 
    { 
      Thread.Sleep(50); 
      Console.writeLine("Hello") 
    } 
} 

不過,因爲你做你該做BeginReceive後的唯一事情就是開始等待在一個循環中無所事事,你可能要考慮擺脫異步電動機回撥,直接撥打Receive並阻止。

+0

你好,謝謝你的回答。我實際上是在while循環期間做了一些事情,但它正在做一堆東西,爲了簡單起見,我不想將它包含在問題中。我會嘗試你的方法,並會讓你知道它是否有效! – George

+0

你好,當我嘗試解決方案時,我得到了以下錯誤:System.Net.Sockets.SocketException(0x80004005):通常允許每個套接字地址(協議/網絡地址/端口)的一個用法 在System.Net.Sockets System.Net.Sockets.Bind(EndPoint localEP) System.Net.Sockets.UdpClient..ctor(IPEndPoint localEP) – George

+1

您只需要調用'CreateClient '有一次,您多次調用ReceiveMessages,但將同一個'UdpClient'作爲參數傳入。 –