2011-05-09 98 views
1

我一直在尋找像我這樣的以前的問題,但似乎我找不到我需要的答案。C#UDP監聽器解除阻塞?或防止被卡住

我的目標是防止我的UDP偵聽器不掛起。我有一個等待消息的UDP監聽器,但如果沒有任何東西可以接收,它就會掛在那裏。

我已閱讀其他線程,他們說我需要設置阻止爲假但我找不到如何設置它。對不起,我只是C#和套接字編程的新手。

這裏是我的聽衆的一部分:

while (true) 
{ 
    try 
    { 
     byte[] data = listener.Receive(ref groupEP); 

     IPEndPoint newuser = new IPEndPoint(groupEP.Address, groupEP.Port); 
     string sData = (System.Text.Encoding.ASCII.GetString(data)); 

    } 
    catch (Exception e) 
    { 
    } 
} 

我的問題是,它只是凍結在下面一行:

byte[] data = listener.Receive(ref groupEP); 
+0

什麼類型是監聽者? – 2011-05-09 05:12:48

回答

5

使用的UDPClient可用的屬性(如果這是你是什麼使用)來確定您是否有網絡隊列中的數據要讀取。

while (true) 
{ 
    try 
    { 
     if (listener.Available > 0) // Only read if we have some data 
     {       // queued in the network buffer. 
      byte[] data = listener.Receive(ref groupEP); 

      IPEndPoint newuser = new IPEndPoint(groupEP.Address, groupEP.Port); 
      string sData = (System.Text.Encoding.ASCII.GetString(data)); 
     } 
    } 
    catch (Exception e) 
    { 
    } 
} 
+0

嗨傑克!正是我需要的..非常感謝你(n_n)_Y – Katherina 2011-05-09 05:25:15

+1

但是,沒有任何循環中斷,它不會實際上等於原始代碼?在Receive()上阻塞,而不是在循環中連續循環(可用)檢查而不是刻錄CPU,不是嗎? – 2011-06-06 07:42:17

+0

在'try {}'子句中添加一個Thread.Sleep(10);並且CPU燒錄完全消失。 – SSpoke 2011-08-31 18:40:24

0
 UdpClient client = new UdpClient(); 
     //Some code goes here ... 
     client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000); 

//這是非常簡單明瞭。