2012-05-15 115 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