tencentSonic框架

来源:互联网 发布:mac safari 强制刷新 编辑:程序博客网 时间:2024/06/07 15:51

这是Soinc 项目的地址https://github.com/Tencent/VasSonic

这个框架做的事情是加速网页的加载速度

传统的WebView加载方式是WebView 初始化后, 然后去请求数据,是串行的操作由于初始化需要时间。所以这里做的事情是让WebView 初始化和请求 数据 并行处理,同时与服务器配合 做好缓存的处理,这里的缓存 分为全部缓存,局部缓存(数据,模板)。获取网络的方式 使用Http(s) 来请求数据 然后通过loadDataWithBaseURL,加载本地download下来的文件,或者是通过loadUrl 但是拦截其资源请求,使用桥节流(InputStream 读取)然后在拦截其资源后返回

android 的传统加载过程
enter image description here

这里是Sonic的流程

enter image description here

直接上图

这里写图片描述

基本的类结构

  • SonicSession::包括缓存数据的获取,服务器回包数据的处理,其中QuickSonicSession 和StandardSonicSession作为其两个子类
  • SonicUtils:作为其数据的重组
  • SonicSessionConnection:作为底层请求数据
  • SonicSessionStream:是Sonic的数据流,是个InputStream
  • SonciSessionClient:是Sonic与WevView的交互,loadUrl 这些
  • 。。。。

这里是 SonicSession 这个处理数据缓存对象的时候为重写的方法

//当本地有缓存的时候做的事情 protected void handleLocalHtml(String localHtml) {    }//当服务器检查本地缓存是最新的时候不需要请求,这个304服务器响应码回复的    protected void handleFlow_304() {    }    //第一次加载    protected void handleFlow_FirstLoad() {    }    //数据更新   protected void handleFlow_DataUpdate() {    }    //模板更新    protected void handleFlow_TemplateChange() {    }
对于QuickSonicSession来说,让WebView 调用的方式为webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); 这里是加载本地文件对于StandardSonicSession来说,让WebView 调用的方式为webView.loadUrl(url);这里是资源文件,但是拦截了资源文件,通过InputStream 来给WEbView 去渲染

两者去区别

  • QuickSonicSession这种方式加载速度比较快,但是由于不能带header(例如csp等),可能会有一些安全问题。
  • 是通过loadUrl,并且在资源拦截的时候返回数据。这种类型相比于QuickSonicSession速度上可能会慢一些(因为资源拦截需要内核底层派发,再到终端进行拦截)。但是这种方式支持在数据返回的时候添加header,所以不存在安全问题

对于SonicSession这个类 ,是多线程的所以采用原子操作

     //当前的状态是否开始请求,请求数据中等    protected final AtomicInteger sessionState = new AtomicInteger(STATE_NONE);    //当前资源是否开始被拦截    protected final AtomicBoolean wasInterceptInvoked = new AtomicBoolean(false);    //是否webview加载网页ok    protected final AtomicBoolean wasOnPageFinishInvoked = new AtomicBoolean(false);

首先

  此处创建了一个SonicSession 同时一块开了一个线程在做请求数据的处理 sonicSession = SonicEngine.getInstance().createSession(url, sessionConfigBuilder.build());最终调用 start()//开个线程跑runSonicFlow();   private void runSonicFlow() {          isWaitingForSessionThread.set(true);        if (STATE_RUNNING != sessionState.get()) {            return;        }         //查看本地有无缓冲(读取本地文件)        String htmlString = SonicCacheInterceptor.getSonicCacheData(this);        boolean hasHtmlCache = !TextUtils.isEmpty(htmlString);        //加载缓存 如果存在缓存StandardSonicSession 做的是准备好InputStream 就是读取(String) 这里做的发送给handler CLIENT_CORE_MSG_PRE_LOAD看下面代码        handleLocalHtml(htmlString);        if (!runtime.isNetworkValid()) {        } else {            //对于本地是否存在完成后已经处理好,此时进行网络连接            handleFlow_Connection(htmlString);        }        // Update session state        switchState(STATE_RUNNING, STATE_READY, true);        isWaitingForSessionThread.set(false);    }
  对于QuickSonicSession 做的逻辑是判断本地有无缓存, 有直接加载 没有直接loadurl  protected void handleLocalHtml(String localHtml) {        Message msg = mainHandler.obtainMessage(CLIENT_CORE_MSG_PRE_LOAD);        if (!TextUtils.isEmpty(localHtml)) {            msg.arg1 = PRE_LOAD_WITH_CACHE;            msg.obj = localHtml;        } else {                    msg.arg1 = PRE_LOAD_NO_CACHE;        }        mainHandler.sendMessage(msg);    } private void handleClientCoreMessage_PreLoad(Message msg) {        switch (msg.arg1) {            case PRE_LOAD_NO_CACHE: {                   //是否第一次调用loadUrl                if (wasLoadUrlInvoked.compareAndSet(false, true)) {                  //直接加载网页但是另一个线程已经在获取数据 然后拦截资源后返回inputSteam                    sessionClient.loadUrl(srcUrl, null);                }            }            break;            case PRE_LOAD_WITH_CACHE: {                 //是否第一次调用loadDataWithBaseUrlAndHeader                if (wasLoadDataInvoked.compareAndSet(false, true)) {                    String html = (String) msg.obj;                    sessionClient.loadDataWithBaseUrlAndHeader(currUrl, html, "text/html", "utf-8", currUrl, getHeaders());                }             }            break;        }    }/////////////////////////////////////////////////////////////对于StandardSonicSession  来说存在直接准备好流修改状态  @Override    protected void handleLocalHtml(String localHtml) {        if (!TextUtils.isEmpty(localHtml)) {            synchronized (webResponseLock) {                pendingWebResourceStream = new ByteArrayInputStream(localHtml.getBytes());            }            //修改当前状态            switchState(STATE_RUNNING, STATE_READY, true);        }    }

WebView 的回调方法

webView.setWebViewClient(new WebViewClient() {            @Override            public void onPageFinished(WebView view, String url) {                super.onPageFinished(view, url);                if (sonicSession != null) {                    sonicSession.getSessionClient().pageFinish(url);                }            }            @TargetApi(21)            @Override            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {                return shouldInterceptRequest(view, request.getUrl().toString());            }            @Override            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {               //请求资源拦截,返回本地请求的inputSteam                if (sonicSession != null) {                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);                }                return null;            }        });
//此时进行连接protected void handleFlow_Connection(String htmlString) {        ....        intent.putExtra(SonicSessionConnection.DNS_PREFETCH_ADDRESS, hostDirectAddress);        //此处默认的实现类是SessionConnectionDefaultImpl ,可以自定义设置案例中提供了OfflinePkgSessionConnection 用来读取本地文件        sessionConnection = SonicSessionConnectionInterceptor.getSonicSessionConnection(this, intent);        //获取响应码        int responseCode = sessionConnection.connect();        if (SonicConstants.ERROR_CODE_SUCCESS == responseCode) {            //成功设置一些cookie 连接时间等        }        if (isDestroyedOrWaitingForDestroy()) {            return;        }        //此处是服务器返回304 采用全部缓存,QuickSonicSession和StandardSonicSession   是直接发送给js状态码304 不需要做操作        if (HttpURLConnection.HTTP_NOT_MODIFIED == responseCode) {            handleFlow_304();            return;        }        if (HttpURLConnection.HTTP_OK != responseCode) {           //失败操作            return;        }        .....        if (TextUtils.isEmpty(htmlString)) {            //这是本地无缓存走的逻辑            handleFlow_FirstLoad();         } else {         //模板文件是否改变            String templateChange = sessionConnection.getResponseHeaderField(SonicSessionConnection.CUSTOM_HEAD_FILED_TEMPLATE_CHANGE);            if (!TextUtils.isEmpty(templateChange)) {                if ("false".equals(templateChange) || "0".equals(templateChange)) {                   //数据更新                    handleFlow_DataUpdate(); // data update                } else {                   //模板更新                    handleFlow_TemplateChange(); // template change                }            } else {               //模板文件的sha1值                String templateTag = sessionConnection.getResponseHeaderField(SonicSessionConnection.CUSTOM_HEAD_FILED_TEMPLATE_TAG);                //检查获取的sha1是否为空同时和本地的sha1比较                if (!TextUtils.isEmpty(templateTag) && !templateTag.equals(sessionData.templateTag)) {                    handleFlow_TemplateChange(); //fault tolerance                } else {                    错误 移除...                }            }        }        saveHeaders(sessionConnection);    }

这里以QuickSonicSession的部分实现为例

   protected void handleFlow_FirstLoad() {   // 获取服务器返回的数据,wasInterceptInvoked 判断是否发起请求资源如果发起直接发哦会        SonicSessionConnection.ResponseDataTuple responseDataTuple = sessionConnection.getResponseData(wasInterceptInvoked, null);        。。。        pendingWebResourceStream = new SonicSessionStream(this, responseDataTuple.outputStream, responseDataTuple.responseStream);        String htmlString = null;        //如果当前读取完成 生成htmlString        if (responseDataTuple.isComplete) {            try {                htmlString = responseDataTuple.outputStream.toString("UTF-8");            } catch (Throwable e) {                pendingWebResourceStream = null;            }        }        boolean hasCacheData = !TextUtils.isEmpty(htmlString);        //  //发送加载消息 如果htmlString 存在调用loadDataWithBaseUrlAndHeader        mainHandler.removeMessages(CLIENT_CORE_MSG_PRE_LOAD);        Message msg = mainHandler.obtainMessage(CLIENT_CORE_MSG_FIRST_LOAD);        msg.obj = htmlString;        msg.arg1 = hasCacheData ? FIRST_LOAD_WITH_CACHE : FIRST_LOAD_NO_CACHE;        mainHandler.sendMessage(msg);        String cacheOffline = sessionConnection.getResponseHeaderField(SonicSessionConnection.CUSTOM_HEAD_FILED_CACHE_OFFLINE);        if (SonicUtils.needSaveData(cacheOffline)) {            try {                if (hasCacheData && !wasLoadUrlInvoked.get() && !wasInterceptInvoked.get()) {                    switchState(STATE_RUNNING, STATE_READY, true);                    Thread.sleep(1500);                    //保存到本地 此处会如果是空就不保存,有则会sonic数据的模版分割                    separateAndSaveCache(htmlString);                }            } catch (Throwable e) {            }        }     } //数据更新 protected void handleFlow_DataUpdate() {        ByteArrayOutputStream output = sessionConnection.getResponseData();        if (output != null) {         //服务器返回 json 是标签和键值对 然后替换                JSONObject serverRspJson = new JSONObject(serverRsp);                 final JSONObject serverDataJson = serverRspJson.optJSONObject("data");                 //这里替换了本地的网页的内容同时返回更新的标签                JSONObject diffDataJson = SonicUtils.getDiffData(id, serverDataJson);                。。。。              //  当前是否已经调用过了loadDataWithBaseUrlAndHeader 如果调用了 直接js给网页,让给他需要更新的json 让js 刷新不需要重新load                   boolean hasSentDataUpdateMessage = false;                 if (wasLoadDataInvoked.get()) {                    if (SonicUtils.shouldLog(Log.INFO)) {                        SonicUtils.log(TAG, Log.INFO, "handleFlow_DataUpdate:loadData was invoked, quick notify web data update.");                    }                    Message msg = mainHandler.obtainMessage(CLIENT_CORE_MSG_DATA_UPDATE);                    if (!OFFLINE_MODE_STORE.equals(cacheOffline)) {                        msg.setData(diffDataBundle);                    }                    mainHandler.sendMessage(msg);                    hasSentDataUpdateMessage = true;                }                //发送如果当前还未loadDataWithBaseUrlAndHeader成功,这里是直接返回本地保存的新的html内容重新调用loadDataWithBaseUrlAndHeader                  if (!hasSentDataUpdateMessage) {                    mainHandler.removeMessages(CLIENT_CORE_MSG_PRE_LOAD);                    Message msg = mainHandler.obtainMessage(CLIENT_CORE_MSG_DATA_UPDATE);                    msg.obj = htmlString;                    mainHandler.sendMessage(msg);                }                。。。        }    }//模板缓存 protected void handleFlow_TemplateChange() {        try {            ByteArrayOutputStream output = new ByteArrayOutputStream();            //检查当前是否已经加载网页成功            SonicSessionConnection.ResponseDataTuple responseDataTuple = sessionConnection.getResponseData(wasOnPageFinishInvoked, output);            ....            String cacheOffline = sessionConnection.getResponseHeaderField(SonicSessionConnection.CUSTOM_HEAD_FILED_CACHE_OFFLINE);            // send CLIENT_CORE_MSG_TEMPLATE_CHANGE message            mainHandler.removeMessages(CLIENT_CORE_MSG_PRE_LOAD);            Message msg = mainHandler.obtainMessage(CLIENT_CORE_MSG_TEMPLATE_CHANGE);            String htmlString = "";            if (responseDataTuple.isComplete) {                htmlString = responseDataTuple.outputStream.toString("UTF-8");                msg.obj = htmlString;            }            if (!OFFLINE_MODE_STORE.equals(cacheOffline)) {                msg.arg1 = TEMPLATE_CHANGE_REFRESH;            }             //有无加载完成htmlString 有则调用loadDataWithBaseUrlAndHeader负责调用loadUrl 然后拦截资源和上述差不多            mainHandler.sendMessage(msg);            if (!responseDataTuple.isComplete) {                responseDataTuple = sessionConnection.getResponseData(wasInterceptInvoked, output);                if (responseDataTuple != null) {                   //准备好桥节流如果当前为读取完 拦截资源后返回改流                    pendingWebResourceStream = new SonicSessionStream(this, responseDataTuple.outputStream, responseDataTuple.responseStream);                } else {                    pendingWebResourceStream = null;                    SonicUtils.log(TAG, Log.ERROR, "session(" + sId + ") handleFlow_TemplateChange error:resourceResponseTuple = null!");                    return;                }            }           ...// 保存文件    }

参考资料 https://www.qcloud.com/community/article/164816001481011853

原创粉丝点击