if(receiveBuffer.position() > 0) { try { /* * Can only go further if at least the length byte of * the InSim Packet exists */ /* * Get the first byte of the buffer * This byte indicates the length of the InSim Packet */ int packetSize = ((short) receiveBuffer.get(0)) & 0xFF; ByteBuffer inSimData; while (receiveBuffer.position() >= packetSize) { // Packet can be read in receiveBuffer.flip(); inSimData = ByteBuffer.allocate(packetSize); byte[] tmpBuffer = new byte[packetSize]; receiveBuffer.get(tmpBuffer); inSimData.put(tmpBuffer); receiveBuffer.compact(); // THE RECEIVED PACKET IS IN isSimData // HERE YOU CAN DO YOUR STUFF WITH THE RECEIVED PACKET } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }