我已经在netbeans中测试了该程序,它工作正常,但在android中不工作。它没有接收任何数据,并在这一行被阻塞,但netbeans中的相同代码能够接收数据。执行时不会抛出错误或异常。谢谢你的建议。
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 = "STARTrn";
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-ALIVErn";
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()。