0

netbeansでプログラムをテストしましたが、うまくいきましたが、アンドロイドでは動作しません。これはデータを受け取っておらず、この行でブロックされていますが、netbeansの同じコードはデータを受け取ることができます。実行中にエラーや例外はスローされません。提案がありがとうございます。Javaで動作していてアンドロイドではないUdpクライアント

import java.net.InetSocketAddress; 
     import java.nio.ByteBuffer; 
     import java.nio.ByteOrder; 
     import java.nio.channels.DatagramChannel; 

     public class StarterThread implements Runnable { 

      Thread t; 
      DatagramChannel channel; 


      StarterThread() { 
       t = new Thread(this, "Starter Thread"); 
       System.out.println("Starter Thread : " + t); 
       t.start(); 
      } 

      public void run() { 
       try { 
        channel = DatagramChannel.open(); 
        channel.connect(new InetSocketAddress("192.168.43.62", 49191)); 
        String newData = "START\r\n"; 
        ByteBuffer buf = ByteBuffer.allocate(190); 
        buf.order(ByteOrder.LITTLE_ENDIAN); 

        buf.clear(); 
        buf.put(newData.getBytes()); 
        buf.flip(); 
        channel.write(buf); 
        int i = 0; 
        while (true) { 
         Log.i("Info", "In while loop"); 
         buf.clear(); 
         Log.i("log i", "" + i); 
         InetSocketAddress client = (InetSocketAddress) channel.receive(buf); 
         buf.flip(); 
         Log.i("TimeStamp", " " + JIHelper.getUnsignedInt(buf.getInt())); 
         System.out.println(new String(buf.array(), "UTF-8")); 
         i++; 
         Log.i("log i", "" + i); 
         if (i % 10 == 0) { 
          newData = "KEEP-ALIVE\r\n"; 
          Log.i("Message sent", "KEEP-ALIVE SENT"); 
          buf.clear(); 
          buf.put(newData.getBytes()); 
          buf.flip(); 
          channel.write(buf); 
          if (i == 100) 
           i = 0; 
         } 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 

     } 

     public class DisplayActivity extends AppCompatActivity { 
     public void sendStartPacket(View view) { 
     new StarterThread(); 
     } 
} 

答えて

-1

Android> = 5.0を使用すると、DatagramChannel.receive()は機能しません。代わりにDatagramChannel.read()を使用する必要があります。

+0

データが利用できない場合はブロック機能が必要ですhttps://docs.oracle.com/javase/7/docs/api/java/nio/channels/DatagramChannel.html#receive(java.nio.ByteBuffer) –

+0

DatagramChannel.configureBlocking()を使用すると、Blocking ModeとしてDatagramChannel.read()を使用できます。 – nakano531

関連する問題