在android中接收UDP数据包

时间:2012-03-05 14:07:10

标签: android udp

我能够在android中执行UDP广播。客户端应发送其IP地址。如果有3到4个客户端在同一网络上运行,我只收到一个客户端的回复。 我想收到所有客户的回复。这是我的广播代码,甚至接收客户发送的数据。

public class Scan4Activity extends Activity {
TextView tv;
int i=-1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i("ggrerrrrrrrggg", "hhaqaaaaaaaaaaahhhhhhh");
    setContentView(R.layout.main);
    //String[] b=;
    try {
        Log.i("ggggg", "hhhhhhhhh");
        String modifiedSentence="received!!!:)";
            main(null);
         Toast.makeText(getApplicationContext(), modifiedSentence, Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        // TODO Auto-generated catch block
         System.out.println("FROM SERVER:error");
        e.printStackTrace();
    }
}

   public void main(String args[]) throws Exception
   {
      DatagramSocket clientSocket = new DatagramSocket();
      InetAddress IPAddress = InetAddress.getByName("255.255.255.255");
      byte[] sendData = new byte[1024];

      String sentence = "hello";//inFromUser.readLine();
      sendData = sentence.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 16789);
      clientSocket.send(sendPacket);
      while(true){
      byte[] receiveData = new byte[1024];
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      clientSocket.receive(receivePacket);
      String modifiedSentence = new String(receivePacket.getData());


      Toast.makeText(getApplicationContext(), modifiedSentence, Toast.LENGTH_SHORT).show();

      System.out.println("FROM SERVER:" + modifiedSentence);



     try{
      clientSocket.close();
     }
     catch(Exception e){

         System.err.println("Cannot Close the Socket" );
     }
   }
 }

所以请帮忙吗?

1 个答案:

答案 0 :(得分:1)

当你测试这个时,你是在2g / 3g网络上进行测试,还是通过wifi进行测试,因为如果你使用2g / 3g进行测试,你很可能在手机上没有静态ip。一些"本地" ip仅在2g / 3g网络内有效,一旦udp包离开移动运营商网络并在互联网上出现,它看起来就像是来自运营商ip,因此所有手机都是如此。