2012-05-15 151 views
0

我想在Android平板電腦上構建UDP客戶端。應用程序可以創建一個套接字中庸之道很好,但是當我試圖把它:從Android平臺發送UDP數據包

public void SendMessage(String message) 
    { 
     sendBuffer = message.getBytes(); 

     packet = new DatagramPacket(sendBuffer, sendBuffer.length, address, 4445); 
     //packet = new DatagramPacket(sendBuffer, sendBuffer.length, address, port); 

     try 
     { 
      socket.send(packet); 
     } 
     catch (IOException ioe) 
     { 
      Log.d("NETWORK", "Failed to send UDP packet due to IOException: " + ioe.getMessage()); 
      ioe.printStackTrace(); 
     } 
     catch(Exception e) 
     { 
      Log.d("NETWORK", "Failed to send UDP packet due to Exeption: " + e.getMessage()); 
      e.printStackTrace(); 
     } 
    } 

的Eclipse彈出一個新窗口說:「源未找到」我已經這樣打印出來的logcat的:

android.os.NetworkOnMainThreadException 
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 
at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) 
at ... 

我想知道如果也許我使用的端口被阻塞或可以阻止我的UDP連接(因爲我已經嘗試了許多不同的端口都具有相同的結果)。我問,因爲logcat的(BlockGuardOS),這可能表明它的阻止一些輸入/輸出

這是實際的初始化這是在這裏:

public ClientSocketThread(String address, int port) 
    {  
     this.port = port; 

     try 
     { 
      this.address = InetAddress.getByName(address); 
      Log.d("NETWORK", "Address successfully resolved"); 
     } 
     catch(UnknownHostException ue) 
     { 
      ue.printStackTrace(); 
      Log.d("NETWORK", "Failed to resolve ip address due to UnknownException: " + ue.getMessage()); 
     } 

     try 
     { 
      this.socket = new DatagramSocket(); 
      Log.d("NETWORK", "UDP Socket successfully created"); 
     } 
     catch(SocketException se) 
     { 
      Log.d("NETWORK", "Failed to create socket due to SocketException: " + se.getMessage()); 
      se.printStackTrace(); 
     } 
    } 
+0

你試圖通過移動網絡發送它的機會嗎?大多數移動網絡阻止UDP數據包AFAIK。 –

+0

不,我通過WiFi連接到我的路由器 – nevero

回答

6
android.os.NetworkOnMainThreadException 

你不再允許做來自主(UI)線程的聯網。您在文檔中始終受到警告,但現在它已被主動困擾。

這個話題已經在SO和其他來源多次被覆蓋。

+1

對於未來找到此線程的人,[this](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception)提供了一個很好的示例正確實現AsyncTask,以便您不在主UI線程上處理。 – Wyatt