First of akk, I know that there is an almost the same question here, but it has no answer. So I'm asking again.
In my Android app, I use a non-blocking UDP socket to do some broadcast job, so I choose DatagramChannel
. As I ran the following code on Samsung GT-P7510(with Android 4.0.4), I get an IndexOutOfBoundsException
which says the buffer is not long enough. But clearly I have already allocate large enough space. Does anyone knows the reason? Any help is appreciated.
Code causes exception:
ByteBuffer bytebuf = ByteBuffer.allocateDirect(1024);
bytebuf.clear();
try {
// LINE causes the Exception!
SocketAddress addr = socketDiscoverChannel.receive(bytebuf);
if (addr != null) {
bytebuf.flip();
InetSocketAddress remoteAddr = (InetSocketAddress) addr;
String remoteIP = remoteAddr.getAddress().getHostAddress();
......
......
} finally {
......
}
Log:
02-26 16:58:22.209: E/AndroidRuntime(4695): FATAL EXCEPTION: IntentService[DaemonListeningService]
02-26 16:58:22.209: E/AndroidRuntime(4695): java.lang.IndexOutOfBoundsException: length=36, offset=0, buffer size=0
02-26 16:58:22.209: E/AndroidRuntime(4695): at java.net.DatagramPacket.setLengthOnly(DatagramPacket.java:234)
02-26 16:58:22.209: E/AndroidRuntime(4695): at java.net.DatagramPacket.setLength(DatagramPacket.java:222)
02-26 16:58:22.209: E/AndroidRuntime(4695): at libcore.io.IoBridge.postRecvfrom(IoBridge.java:528)
02-26 16:58:22.209: E/AndroidRuntime(4695): at libcore.io.IoBridge.recvfrom(IoBridge.java:516)
02-26 16:58:22.209: E/AndroidRuntime(4695): at java.nio.DatagramChannelImpl.receiveDirectImpl(DatagramChannelImpl. java:232)
02-26 16:58:22.209: E/AndroidRuntime(4695): at java.nio.DatagramChannelImpl.receive(DatagramChannelImpl.java:185)
02-26 16:58:22.209: E/AndroidRuntime(4695): at com.zisync.daemon.DaemonListeningService.startListening( DaemonListeningService.java:261)
02-26 16:58:22.209: E/AndroidRuntime(4695): at com.zisync.daemon.DaemonListeningService.onHandleIntent( DaemonListeningService.java:98)
02-26 16:58:22.209: E/AndroidRuntime(4695): at android.app.IntentService$ServiceHandler.handleMessage(IntentService. java:65)
02-26 16:58:22.209: E/AndroidRuntime(4695): at android.os.Handler.dispatchMessage(Handler.java:99)
02-26 16:58:22.209: E/AndroidRuntime(4695): at android.os.Looper.loop(Looper.java:137)
02-26 16:58:22.209: E/AndroidRuntime(4695): at android.os.HandlerThread.run(HandlerThread.java:60)