Udp客户端工作在Java但不是在Android
问题描述:
我已经在NetBeans中测试了程序,它工作正常,但它不工作在Android。它没有收到任何数据并在此行被阻止,但netbeans中的相同代码能够接收数据。执行时不会抛出错误或异常。感谢您的任何建议。Udp客户端工作在Java但不是在Android
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();
}
}
答
如果使用Android> = 5.0,DatagramChannel.receive()不起作用。你需要使用DatagramChannel.read()来代替。
如果数据不可用,我需要阻止功能https://docs.oracle.com/javase/7/docs/api/java/nio/channels/DatagramChannel.html#receive(java.nio.ByteBuffer) –
您可以使用DatagramChannel.configureBlocking()将DatagramChannel.read()用作阻止模式。 – nakano531